if語句
一、if語句的格式
語句塊必須有相同的縮排。
語句塊必須比if,elif,else多一層縮排
# 如果條件成立則執行語句塊1,# 否則 如果條件2成立則執行語句塊2# 其他情況執行語句塊3# elis和else部分是可選的if 條件1: 語句塊1elif 條件2: 語句塊2else: 語句塊3
二、執行個體
i = 10if i == 3: print ' i 是3.' print "我也是在if之後執行的。"elif i < 3: print 'i < 3'else: print '其他情況。'print '列印結束。'
三、注意事項
1. python中沒有switch語句, switch可以使用if...elif...else實現2. if, elif, else之後必須要有冒號(:), 之後的代碼需要增加一層縮排
while迴圈
只要在一個條件為真的情況下,while語句允許你重複執行一塊語句。while語句是所謂 迴圈 語句的一個例子。while語句有一個可選的else從句。
使用while語句
例6.2 使用while語句
| 代碼如下 |
複製代碼 |
#!/usr/bin/python # Filename: while.py number = 23 running = True while running: guess = int(raw_input('Enter an integer : ')) if guess == number: print 'Congratulations, you guessed it.' running = False # this causes the while loop to stop elif guess < number: print 'No, it is a little higher than that' else: print 'No, it is a little lower than that' else: print 'The while loop is over.' # Do anything else you want to do here print 'Done' (源檔案:code/while.py) 輸出 $ python while.py Enter an integer : 50 No, it is a little lower than that. Enter an integer : 22 No, it is a little higher than that. Enter an integer : 23 Congratulations, you guessed it. The while loop is over. Done |
for語句
for..in是另外一個迴圈語句,它在一序列的對象上 遞迴 即逐一使用隊列中的每個項目。我們會在後面的章節中更加詳細地學習序列。
使用for語句
例6.3 使用for語句
| 代碼如下 |
複製代碼 |
#!/usr/bin/python # Filename: for.py for i in range(1, 5): print i else: print 'The for loop is over' 輸出 $ python for.py 1 2 3 4 The for loop is over |
break和continue語句
break語句是用來 終止 迴圈語句的,即哪怕迴圈條件沒有稱為False或序列還沒有被完全遞迴,也停止執行迴圈語句。
一個重要的注釋是,如果你從for或while迴圈中 終止 ,任何對應的迴圈else塊將不執行。
使用break語句
例6.4 使用break語句
| 代碼如下 |
複製代碼 |
#!/usr/bin/python # Filename: break.py while True: s = raw_input('Enter something : ') if s == 'quit': break print 'Length of the string is', len(s) print 'Done' |
continue語句被用來告訴Python跳過當前迴圈塊中的剩餘語句,然後 繼續 進行下一輪迴圈。
使用continue語句
例6.5 使用continue語句
| 代碼如下 |
複製代碼 |
#!/usr/bin/python # Filename: continue.py while True: s = raw_input('Enter something : ') if s == 'quit': break if len(s) < 3: continue print 'Input is of sufficient length' # Do other kinds of processing here... (源檔案:code/continue.py) 輸出 $ python continue.py Enter something : a Enter something : 12 Enter something : abc Input is of sufficient length Enter something : quit |