Python流程控制之while循环
一、基本使用
count = 2 while count < 4: print(count) count += 1 print('顶级循环')
二、退出循环的两种方式
1、将条件改为False,下次才结束
username = 'brynn' userpwd = '123' tag = True
while tag: name = input('your name :') pwd = input('your password :') if name == username and pwd == userpwd: print('success') tag=False else: print('False and input again') print('end')
2、break,只要运行到break,就会立即终止本层循环。
username = 'brynn' userpwd = '123' while 1: name = input('your name :') pwd = input('your password :') if name == username and pwd == userpwd: print('success') break else: print('False and input again') print('end')
三、结束本次循环,直接进入下一次:while+continue
count=0 while count<6: if count==4: count+=1 continue print(count) count+=1 # 结果 # 0 # 1 # 2 # 3 # 5
四、while+else
count = 0 while count < 6: if count == 4: count += 1 continue print(count) count += 1 else: print('^.^') # 0 # 1 # 2 # 3 # 5 # ^.^

浙公网安备 33010602011771号