基本语法:
while condition:
code...
else:
code...
示例:
1.输出1到10,不包括7
n = 1
while n < 11:
if n == 7:
pass
else:
print(n)
n = n+1
2.计算1-100所有数之和
n = 1
s = 0
while n < 101:
s = s + n
n = n + 1
print(s)
3.计算1-2+3-4+5-6...99
n = 1
s = 0
while n < 101:
if n % 2 == 0:
s = s - n
else:
s = s + n
n = n + 1
print(s)
continue && break
continue表示跳出当前循环,不再执行之后的代码
break表示跳出整个循环
示例4:输入登陆用户名密码,只有三次输错的机会
count = 0
while count < 3:
username = input("请输入用户名:")
password = input("请输入密码:")
if username == "wangjie" and password == "123456":
print("欢迎登陆")
break
else:
print("用户名或密码错误")
count = count + 1
else:
print("请稍后再试")