標籤:重複 div color image ase blog 退出 pre print
Python While 迴圈語句
Python 編程中 while 語句用於迴圈執行程式,即在某條件下,迴圈執行某段程式,以處理需要重複處理的相同任務。其基本形式為:
while 判斷條件: 執行語句……
執行語句可以是單個語句或語句塊。判斷條件可以是任何錶達式,任何非零、或非空(null)的值均為true。
當判斷條件假false時,迴圈結束。
執行流程圖如下:
while 語句時還有另外兩個重要的命令 continue,break 來跳過迴圈,continue 用於跳過該次迴圈,break 則是用於退出迴圈,此外"判斷條件"還可以是個常值,表示迴圈必定成立,具體用法如下:
1 #coding=utf-8 2 ‘‘‘ 3 @author:Nelson.huang 4 @Date : 2017.07,25 5 @Funtion: while迴圈的練習: 6 使用者輸入一個小於1000的數字,輸出所有結果,並停在使用者輸入的結果這裡,並且詢問使用者是否繼續迴圈。 7 如果使用者輸入非‘N’的字串,繼續迴圈,並再次要求使用者輸入一個停下來的數字,繼續。 8 9 ‘‘‘10 11 print_num = input(‘Please input the count :‘)12 count = 013 while count < 1000:14 if count == print_num:15 print "There you got the number:", count16 choice = raw_input(‘Do you want to continue to loop?(y/n):‘)17 if choice == ‘n‘:18 break19 else:20 print_num = input(‘Please re-input the count:‘)21 22 if print_num < count:23 print ‘your num is passed, please re-input:‘24 print_num = input(‘Please input the count :‘)25 continue26 27 else:28 print ‘loop:‘, count29 30 count +=1
執行結果:
C:\Python27\python.exe C:/Work/python/while.py
Please input the count :5
loop: 0
loop: 1
loop: 2
loop: 3
loop: 4
There you got the number: 5
Do you want to continue to loop?(y/n):y
Please re-input the count:8
loop: 5
loop: 6
loop: 7
There you got the number: 8
Do you want to continue to loop?(y/n):y
Please re-input the count:4
your num is passed, please re-input:
Please input the count :16
loop: 8
loop: 9
loop: 10
loop: 11
loop: 12
loop: 13
loop: 14
loop: 15
There you got the number: 16
Do you want to continue to loop?(y/n):
python學習之while迴圈