while在Python中表示条件循环。符合条件则循环执行。否则跳出循环。
while循环的语法:while循环又称为条件循环,循环的次数取决于条件
语法1:
while 条件:
子代码
子代码
print('start....') while True: name=input('please your name>>: ') pwd=input('please your password>>: ') if name == 'egon' and pwd == '123': print('login successful') else: print('user or password error') print('end...')
#该循环为死循环,因为其判断条件一直为True。无法跳出循环。
结束循环的方式:
1、设置循环次数的条件变量,同时在循环体中对变量进行操作,以在一定次数后结束循环。
count=1 while count < 6: print(count) count+=1 #1 2 3 4 5
或是
tag= True count = 0 while tag: if count ==3: tag = False print(count) count+=1 #0 1 2 3
还有就是使用break,强行从本层循环中跳出。使得循环结束。
count = 0 while count<3: print(count) if count ==1: break count+=1 #0 1
while 还可以与else连用,while循环正常结束循环,而非被break强行结束,则会执行else中的代码块。
count = 0 while count < 3: print(count) count +=1 if count==3: break else: print('while循环被完全执行') #0 1 2 #while循环被完全执行 count = 0 while count < 3: print(count) count +=1 if count==2: break else: print('while循环被完全执行') #0 1 else的代码没有被执行。
while 还可与continue连用,continue的意思为跳出本次循环,进入下次循环。
count=1 while count < 6: if count == 4: count+=1 continue # 只能在cotinue同一级别之前加代码 print(count) count+=1 #1 2 3 5
不应该将continue作为循环体最后一步执行的代码。最后一步的意思是指当执行该步操作后,进入下次循环的操作被称之循环的最后一步执行代码。
while循环的嵌套和跳出循环的方法:
1 while循环的嵌套 2 name_of_db='egon' 3 pwd_of_db='123' 4 print('start....') 5 count=0 6 while count <= 2: #count=3 7 name=input('please your name>>: ') 8 pwd=input('please your password>>: ') 9 if name == name_of_db and pwd == pwd_of_db: 10 print('login successful') 11 while True: 12 print(""" 13 1 浏览商品 14 2 添加购物车 15 3 支付 16 4 退出 17 """) 18 choice=input('请输入你的操作: ') #choice='1' 19 if choice == '1': 20 print('开始浏览商品....') 21 elif choice == '2': 22 print('正在添加购物车....') 23 elif choice == '3': 24 print('正在支付....') 25 elif choice == '4': 26 break 27 break 28 else: 29 print('user or password err') 30 count+=1 31 else: 32 print('输错的次数过多')
这个while循环使用的是break方法跳出循环的方法。但是缺点是若是多层嵌套的话,会使得嵌套跳出break的位置难以确定,增加书写困难。
通常情况下使用的变量的方法来一次跳出所有循环。
name_of_db='egon' pwd_of_db='123' tag=True print('start....') count=0 while tag: if count == 3: print('尝试次数过多') break name=input('please your name>>: ') pwd=input('please your password>>: ') if name == name_of_db and pwd == pwd_of_db: print('login successful') while tag: print(""" 1 浏览商品 2 添加购物车 3 支付 4 退出 """) choice=input('请输入你的操作: ') #choice='1' if choice == '1': print('开始浏览商品....') elif choice == '2': print('正在添加购物车....') elif choice == '3': print('正在支付....') elif choice == '4': tag=False else: print('user or password err') count+=1 print('end...')