一、語法
循環就是一個重復的過程,我們人需要重復干一個活,那么計算機也需要重復干一個活。ATM驗證失敗,那么計算機會讓我們再一次輸入密碼。這個時候就得說出我們的wile循環,while循環又稱為條件循環。
while 條件
code 1
code 2
code 3
...
while True:
print('*1'*100)
print('*2'*100)
# 實現ATM的輸入密碼重新輸入的功能
while True:
user_db = 'nick'
pwd_db = '123'
inp_user = input('username: ')
inp_pwd = input('password: ')
if inp_user == user_db and pwd_db == inp_pwd:
print('login successful')
else:
print('username or password error')
上述代碼雖然實現了功能,但是用戶密碼輸對了,他也會繼續輸入。
二、while + break
break的意思是終止掉當前層的循環,執行其他代碼。
while True:
print('1')
print('2')
break
print('3')
1
2
上述代碼的break毫無意義,循環的目的是為了讓計算機和人一樣工作,循環處理事情,而他直接打印1和2之后就退出循環了。而我們展示下有意義的while+break代碼的組合。
while True:
user_db = 'nick'
pwd_db = '123'
inp_user = input('username: ')
inp_pwd = input('password: ')
if inp_user == user_db and pwd_db == inp_pwd:
print('login successful')
break
else:
print('username or password error')
print('退出了while循環')
username: nick
password: 123
login successful
退出了while循環
三、while + continue
continue的意思是終止本次循環,直接進入下一次循環
n = 1
while n < 4:
print(n)
n += 1
1
2
3
n = 1
while n < 10:
if n == 8:
# n += 1 # 如果注釋這一行,則會進入死循環
continue
print(n)
n += 1
continue不能加在循環體的最后一步執行的代碼,因為代碼加上去毫無意義,如下所示的continue所在的位置就是毫無意義的。ps:注意是最后一步執行的代碼,而不是最后一行。
while True:
if 條件1:
code1
code2
code3
...
else:
code1
code2
code3
...
continue
四、while循環的嵌套
ATM密碼輸入成功還需要進行一系列的命令操作,比如取款,比如轉賬。並且在執行功能結束后會退出命令操作的功能,即在功能出執行輸入q會退出輸出功能的while循環並且退出ATM程序。
# 退出內層循環的while循環嵌套
while True:
user_db = 'nick'
pwd_db = '123'
inp_user = input('username: ')
inp_pwd = input('password: ')
if inp_user == user_db and pwd_db == inp_pwd:
print('login successful')
while True:
cmd = input('請輸入你需要的命令:')
if cmd == 'q':
break
print(f'{cmd} 功能執行')
else:
print('username or password error')
print('退出了while循環')
# 退出雙層循環的while循環嵌套
while True:
user_db = 'nick'
pwd_db = '123'
inp_user = input('username: ')
inp_pwd = input('password: ')
if inp_user == user_db and pwd_db == inp_pwd:
print('login successful')
while True:
cmd = input('請輸入你需要的命令:')
if cmd == 'q':
break
print(f'{cmd} 功能執行')
break
else:
print('username or password error')
print('退出了while循環')
username: nick
password: 123
login successful
請輸入你需要的命令:q
退出了while循環
五、tag控制循環退出
# tag控制循環退出
tag = True
while tag:
user_db = 'nick'
pwd_db = '123'
inp_user = input('username: ')
inp_pwd = input('password: ')
if inp_user == user_db and pwd_db == inp_pwd:
print('login successful')
while tag:
cmd = input('請輸入你需要的命令:')
if cmd == 'q':
tag = False
print(f'{cmd} 功能執行')
else:
print('username or password error')
print('退出了while循環')
username: nick
password: 123
login successful
請輸入你需要的命令:q
q 功能執行
退出了while循環
六、while + else
while+else:else會在while沒有被break時才會執行else中的代碼。
# while+else
n = 1
while n < 3:
print(n)
n += 1
else:
print('else會在while沒有被break時才會執行else中的代碼')
1
2
else會在while沒有被break時才會執行else中的代碼