跳轉到內容

Python 程式設計入門/Python 程式設計 - 控制結構

來自華夏公益教科書,自由的教科書,共建自由世界

4. 控制結構

[編輯 | 編輯原始碼]

一組動作定義了事件流,由流程圖決定。在 Python 程式設計中,所有非“None”的值都返回 True,而具有“None”值的變數則返回 False。

4.1. if 語句

[編輯 | 編輯原始碼]

最簡單的控制 if 語句在條件滿足時返回 True 值。有一個簡單的單行 if 條件,接著是 if-else,然後是 if-elif 語句。

   >>> var = 100
   >>> if var==100:

print "yay! 變數確實是 100!!!"

   yay! the variable is truly 100!!!
   >>>
   >>> 
   >>> if (var==100): print "value is 100, its looks great!"
   value is 100, its looks great!
   >>>
   var = 100
   if var == 100:
       print "yay! the variable is truly 100"
   else:
       print "Nope! Better luck next time!!!!"
   >>>var=10
   >>> if var == 100:
           print "yay! the variable is truly 100"
       else:
           print "Nope! Better luck next time!!!!"
   Nope! Better luck next time!!!!

4.2. for 迴圈

[編輯 | 編輯原始碼]

Python 中的“for”迴圈會對一個程式碼塊執行已知次數的迭代。Python 中“for”迴圈的特殊之處在於,可以對列表、字典、字串變數中的專案數量進行迭代,以特定步驟數對特定範圍的數字進行迭代,以及對元組中存在的專案數量進行迭代。

   >>> a=(10,20,30,40,50)
   >>> for b in a:
   print "square of " + str(b) + " is " +str(b*b)
   square of 10 is 100
   square of 20 is 400
   square of 30 is 900
   square of 40 is 1600
   square of 50 is 2500
   >>> c=["new", "string", "in", "python"]
   >>> for d in c:
           print "the iteration of string is %s" %d
   the iteration of string is new
   the iteration of string is string
   the iteration of string is in
   the iteration of string is python
   >>>
   >>> for i in range(10):

print " "+str(i)+" 的值為 "+str(i)

   the value of 0 is 0
   the value of 1 is 1
   the value of 2 is 2
   the value of 3 is 3
   the value of 4 is 4
   the value of 5 is 5
   the value of 6 is 6
   the value of 7 is 7
   the value of 8 is 8
   the value of 9 is 9
   >>> a={'a':10,'b':20,'c':30}
   >>> for k in a:
       	print "the key is %s and the value is %d" %(k,a[k])
   the key is a and the value is 10
   the key is c and the value is 30
   the key is b and the value is 20

4.3. while 迴圈

[編輯 | 編輯原始碼]

while 迴圈在條件語句返回 true 時執行。在執行程式碼塊之前,每次都會評估條件語句,並且在條件語句返回 false 的那一刻,執行就會停止。

   >>> count = 0
   >>> while (count<9):
       print "the count is at iteration %d" %count
       count+=1
   the count is at iteration 0
   the count is at iteration 1
   the count is at iteration 2
   the count is at iteration 3
   the count is at iteration 4
   the count is at iteration 5
   the count is at iteration 6
   the count is at iteration 7
   the count is at iteration 8
華夏公益教科書