1、概念:
條件循環是指:一個結構,致使一個程序要重複必定次數,當條件變爲假,則循環結束。python
2、語法:less
1 while 條件: 2 3 # 循環體 4 5 # 若是條件爲真,那麼循環體則執行 6 # 若是條件爲假,那麼循環體不執行
執行語句能夠是
a、單個語句或語句塊。
b、判斷條件是以任何表達式。
c、任何非零、或非空(null)的值均爲True。ide
當判斷條件爲false時,循環結束:spa
執行流程圖:code
1 #!/usr/bin/env python 2 # -*- coding:utf8 -*- 3 4 count = 0 5 while (count < 9): 6 print('The count is:'), count 7 count = count + 1 8 print("Good bye!") 9 10 11 輸出結果: 12 The count is: 0 13 The count is: 1 14 The count is: 2 15 The count is: 3 16 The count is: 4 17 The count is: 5 18 The count is: 6 19 The count is: 7 20 The count is: 8 21 Good bye!
while 語句時還有另外兩個重要的命令 continue,break 來跳過循環:
continue 用於跳過該次循環
break 則是用於退出循環
此外"判斷條件"還能夠是個常值,表示循環一定成立,具體用法以下:blog
1 i = 1 2 while i < 10: 3 i += 1 4 if i%2 > 0: # 非雙數時跳過輸出 5 continue 6 print (i) # 輸出雙數二、四、六、八、10 7 8 9 i = 1 10 while 1: # 循環條件爲1一定成立 11 print (i) # 輸出1~10 12 i += 1 13 if i > 10: # 當i大於10時跳出循環 14 break
1 #!/usr/bin/python 2 #coding=utf-8 3 4 var = 1 5 6 while var == 1 : # 該條件永遠爲true,循環將無限執行下去 7 num = raw_input("Enter a number :") #表示須要界面輸入值,用於交互print "You entered: ", num #num是上面的變量,表示輸人值在輸出 8 9 print ("Good bye!")
注意:以上的無限循環你可使用 CTRL+C 來中斷循環。(循環無止境,直到內存撐爆,會致使系統雪崩!)內存
while.....else表示這樣的意思:utf-8
1 #!/usr/bin/python 2 3 count = 0 4 while count < 5: 5 print(count, "is less than 5") 6 count = count + 1 7 else : 8 print(count,"is not less than 5") 9 10 11 輸出結果: 12 0 is less than 5 13 1 is less than 5 14 2 is less than 5 15 3 is less than 5 16 4 is less than 5 17 5 is not less than 5
相似if語句的語法,若是你的while循環體中只有一條語句,你能夠將該語句與while寫在同一行中, 以下所示:input
1 #!/usr/bin/python 2 3 flag = 1 4 while (flag): print 'Given flag is really true!' 5 6 7 輸出結果: 8 print "Good bye!" 9 10 注意:以上的無限循環你可使用 CTRL+C 來中斷循環。