日韩 亚洲一区二_久久vs国产综合色大全_国产精品福利在线_欧美在线一级A片免费观看欧美在线_女同性毛片60分钟

您現(xiàn)在所在的位置:首頁(yè) >學(xué)習(xí)資源 > Python全棧+人工智慧入門(mén)教材 > Python基礎(chǔ)入門(mén)教程35:Python while 循環(huán)語句

Python基礎(chǔ)入門(mén)教程35:Python while 循環(huán)語句

來(lái)源:奇酷教育 發(fā)表於:

Python開(kāi)發(fā) Python教程 Python基礎(chǔ)

  Python While 循環(huán)語句
  Python 編程中 while 語句用於循環(huán)執(zhí)行程序,即在某條件下,循環(huán)執(zhí)行某段程序,以處理需要重複處理的相同任務(wù)。其基本形式為:
  while 判斷條件: 執(zhí)行語句……
  執(zhí)行語句可以是單個(gè)語句或語句塊。判斷條件可以是任何表達(dá)式,任何非零、或非空(null)的值均為true。
  當(dāng)判斷條件假false時(shí),循環(huán)結(jié)束。
  執(zhí)行流程圖如下:


  實(shí)例
  #!/usr/bin/python count = 0while (count < 9): print 'The count is:', count count = count + 1 print "Good bye!"
  運(yùn)行實(shí)例 »
  以上代碼執(zhí)行輸(shū)出結(jié)果:

  The count is: 0The count is: 1The count is: 2The count is: 3The count is: 4The count is: 5The count is: 6The count is: 7The count is: 8Good bye!
  while 語句時(shí)還有另外兩(liǎng)個(gè)重要的命令 continue,break 來(lái)跳過(guò)循環(huán),continue 用於跳過(guò)該次循環(huán),break 則是用於退出循環(huán),此外"判斷條件"還可以是個(gè)常值,表示循環(huán)必定成立,具體用法如下:
  # continue 和 break 用法 i = 1while i < 10: i += 1 if i%2 > 0: # 非雙數(shù)時(shí)跳過(guò)輸(shū)出 continue print i # 輸(shū)出雙數(shù)2、4、6、8、10 i = 1while 1: # 循環(huán)條件為1必定成立 print i # 輸(shū)出1~10 i += 1 if i > 10: # 當(dāng)i大於10時(shí)跳出循環(huán) break
  

無(wú)限循環(huán) 
  如果條件判斷語句永遠(yuǎn)為 true,循環(huán)將會(huì)無(wú)限的執(zhí)行下去,如下實(shí)例:
  實(shí)例
  #!/usr/bin/python# -*- coding: UTF-8 -*- var = 1while var == 1 : # 該條件永遠(yuǎn)為true,循環(huán)將無(wú)限執(zhí)行下去 num = raw_input("Enter a number :") print "You entered: ", num print "Good bye!"
  以上實(shí)例輸(shū)出結(jié)果:
  Enter a number :20You entered: 20Enter a number :29You entered: 29Enter a number :3You entered: 3Enter a number between :Traceback (most recent call last): File "test.py", line 5, in 
 num = raw_input("Enter a number :")KeyboardInterrupt
  注意:以上的無(wú)限循環(huán)你可以使用 CTRL+C 來(lái)中斷循環(huán)。
  

循環(huán)使用 else 語句 
  在 python 中,while … else 在循環(huán)條件為 false 時(shí)執(zhí)行 else 語句塊:
  實(shí)例
  #!/usr/bin/python count = 0while count < 5: print count, " is less than 5" count = count + 1else: print count, " is not less than 5"
  以上實(shí)例輸(shū)出結(jié)果為:
  0 is less than 51 is less than 52 is less than 53 is less than 54 is less than 55 is not less than 5
  

簡(jiǎn)單語句組 
  類(lèi)似 if 語句的語法,如果你的 while 循環(huán)體中只有一條語句,你可以將該語句與while寫(xiě)在同一行中, 如下所示:
  實(shí)例
  #!/usr/bin/python flag = 1 while (flag): print 'Given flag is really true!' print "Good bye!"
  注意:以上的無(wú)限循環(huán)你可以使用 CTRL+C 來(lái)中斷循環(huán)。