基本語法:
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("請稍后再試")
