Python 學習筆記(十一)Python語句(三),學習筆記python語句
While 迴圈語句
用於迴圈執行程式,即在某條件下,迴圈執行某段程式,以處理需要重複處理的相同任務。
文法:
while 判斷條件: 執行語句……
執行語句可以是單個語句或語句塊。判斷條件可以是任何錶達式,任何非零、或非空(null)的值均為true。
當判斷條件假false時,迴圈結束。
樣本:for迴圈實現猜字遊戲
1 #! /usr/bin/env python 2 #! coding:utf-8 3 4 5 """ 6 一個猜字遊戲:隨機產生一個數字,使用者每次輸入一個數字,來猜這個數字是否為隨機數。 7 for實現 8 """ 9 10 import random11 12 num =random.randint(1,100) #return a int [1,100]13 #注意:for 迴圈得有個問題,得知道迴圈多少次14 for i in range(0,100):15 input_num =int(raw_input("Please input a int:"))16 if input_num ==num:17 print "ok,you are right"18 print num19 break #從當前迴圈體跳出20 elif input_num>num:21 print "input number is larger than int."22 else:23 print "input number is smaller than int."
while 實現猜字遊戲
1 #! /usr/bin/env python 2 #! coding:utf-8 3 4 5 """ 6 while expression: 7 do something 8 """ 9 10 import random11 12 num =random.randint(1,100) #return a int [1,100]13 14 15 i =016 while i<10: #此處也可修改為1,直到猜中才會停止17 print i18 input_num =int(raw_input("Please input a int:"))19 if input_num ==num:20 print "ok,you are right"21 print num22 break #從當前迴圈體跳出,執行迴圈體後面的內容23 elif input_num>num:24 print "input number is larger than int."25 else:26 print "input number is smaller than int."27 28 i +=1
break
break語句用來終止迴圈語句,即迴圈條件沒有False條件或者序列還沒被完全遞迴完,也會停止執行迴圈語句。
break語句用在while和for迴圈中。
continue
continue 語句跳出本次迴圈,而break跳出整個迴圈。
continue 語句用來告訴Python跳過當前迴圈的剩餘語句,然後繼續進行下一輪迴圈。
continue語句用在while和for迴圈中。
樣本:continue
1 #! /usr/bin/env python 2 #! coding:utf-8 3 4 a =9 5 while a: 6 if a%2==0: 7 a -=1 8 continue #如果是偶數,就返回迴圈的開始 9 print a 10 else:11 print "%d is odd number "%a #如果是奇數,就列印出來12 a -=113
while ... else
1 #! /usr/bin/env python2 #! coding:utf-83 4 count = 05 while count < 5:6 print count," is less than 5"7 count =count+18 else:9 print count," is not less than 5"
for ... else
1 #! /usr/bin/env python 2 #! coding:utf-8 3 4 #開平方 5 from math import sqrt 6 7 for n in range(99,1,-1): 8 root = sqrt(n) 9 if root == int(root):10 print n11 break12 else:13 print "Nothing."