語法:
while 條件:
代碼1
代碼2
代碼3python
while True: name=input('please input your name: ') pwd=input('please input your password: ') if name == 'egon' and pwd == '123': print('login successful') else: print('username or password error')
結束while循環的兩種方式blog
方式一:條件改成False,
在條件改成False時不會當即結束掉循環,而是要等到下一次循環判斷條件時纔會生效input
tag=True while tag: name=input('please input your name: ') pwd=input('please input your password: ') if name == 'egon' and pwd == '123': print('login successful') tag=False else: print('username or password error') print('===>')
方式二:while+break
break必定要放在循環體內,一旦循環體執行到break就會當即結束本層循環class
while True: name=input('please input your name: ') pwd=input('please input your password: ') if name == 'egon' and pwd == '123': print('login successful') break else: print('username or password error') print('===>>>>>') print('===>>>>>')
while+continue:結束本次循環,直接進入下一次循環循環
# 示例一語法
count=1 while count < 6: #count=6 if count == 4: count += 1 continue print(count) count+=1
# 示例二:error
while True: name=input('please input your name: ') pwd=input('please input your password: ') if name == 'egon' and pwd == '123': print('login successful') break else: print('username or password error') # continue # 此處加continue無用
瞭解知識
while + else:查詢
while 條件:
代碼1
代碼2
代碼3
else:
在循環結束後,而且在循環沒有被break打斷過的狀況下,纔會執行else的代碼word
tag=True while tag: print(1) print(2) print(3) # tag=False break else: print('else的代碼')
while 條件1:
while 條件2:
代碼1
代碼2
代碼3di
示範一:
while True: name=input('please input your name: ') pwd=input('please input your password: ') if name == 'egon' and pwd == '123': print('login successful') while True: print(""" 0 退出 1 取款 2 轉帳 3 查詢 """) choice=input('請輸入您要執行的操做:') #choice='1' if choice == '0': break elif choice == '1': print('取款。。。') elif choice == '2': print('轉帳。。。') elif choice == '3': print('查詢') else: print('輸入指令錯誤,請從新輸入') break else: print('username or password error')
# 示範二:
tag=True while tag: name=input('please input your name: ') pwd=input('please input your password: ') if name == 'egon' and pwd == '123': print('login successful') while tag: print(""" 0 退出 1 取款 2 轉帳 3 查詢 """) choice=input('請輸入您要執行的操做:') #choice='1' if choice == '0': tag=False elif choice == '1': print('取款。。。') elif choice == '2': print('轉帳。。。') elif choice == '3': print('查詢') else: print('輸入指令錯誤,請從新輸入') else: print('username or password error')