While循環是喲中利用條件語句,不斷的執行某一段代碼塊,達到批量操做輸出等一系列的操做,直到條件不知足或者被強制退出爲止。html
其工做流程以下: (圖片來源菜鳥教程:http://www.runoob.com/python/python-while-loop.html )python
咱們來看一個例子:less
current_number = 10 while current_number <= 20: print("Current number is : " + str(current_number)) current_number += 1 print("Final number: " + str(current_number)) ''' 輸出: Current number is : 10 Current number is : 11 Current number is : 12 Current number is : 13 Current number is : 14 Current number is : 15 Current number is : 16 Current number is : 17 Current number is : 18 Current number is : 19 Current number is : 20 Final number: 21 '''
咱們能夠看到 變量current_number 的初始值爲10, 在小於等於20的狀況下,不斷的被打印,被增加,直至增加到21的時候,跳出了循環。oop
咱們也能夠使用標誌,好比True,False 等布爾值來進行循環:ui
flag = True while flag: number = int(input("Input a number less than 10:\n")) if number < 10: flag = True else: flag = False print("The game is end...") ''' 輸出: Input a number less than 10: 2 Input a number less than 10: 11 The game is end... Final number: 21 '''
使用 break 退出循環。在while循環中,你能夠經過特定的條件語句,選擇終止循環,再也不繼續運行餘下的代碼。spa
flag = True while flag: city = input("Input a city which you like: \n" + "Input 'Q' to quit...\n") if city == 'Q': break else: print("You like " + city) print("Thanks for your information.") ''' 輸出: Input a city which you like: Input 'Q' to quit... ShangHai You like ShangHai Input a city which you like: Input 'Q' to quit... HangZhou You like HangZhou Input a city which you like: Input 'Q' to quit... Q Thanks for your information. '''
使用 continue 再也不繼續執行餘下的代碼塊,返回到循環開頭,繼續下一輪循環。code
number = 0 while number <= 10: if number % 2 == 0: print("The number is even: " + str(number)) number += 1 continue print("Next...") else: number += 1 ''' 輸出: The number is even: 0 The number is even: 2 The number is even: 4 The number is even: 6 The number is even: 8 The number is even: 10 '''
循環也能夠和else 一塊兒使用:orm
number = 0 while number <= 10: if number % 2 == 0: print("The number is even: " + str(number)) number += 1 continue print("Next...") else: number += 1 else: print("The number is equal or more than 10, stop loop.") ''' 輸出: The number is even: 0 The number is even: 2 The number is even: 4 The number is even: 6 The number is even: 8 The number is even: 10 The number is equal or more than 10, stop loop. '''
使用while 操做列表 Listhtm
peoples = ['Ralf', 'Clark', 'Leon'] while peoples: people = peoples.pop() print(people) ''' 輸出: Leon Clark Ralf '''
peoples = ['Ralf', 'Clark', 'Leon', 'Terry'] while 'Terry' in peoples: peoples.remove('Terry') print(peoples) ''' 輸出: ['Ralf', 'Clark', 'Leon'] '''
while循環語句能夠解決程序中須要重複執行的操做。其循環執行的次數由循環條件肯定,當循環條件知足時,重複執行某程序段,直到循環條件不成立爲止。反覆執行的程序段稱爲循環體,循環條件必需要在循環體中改變,不然可能會出現無限循環的結果blog