簡介
在到目前為止我們所見到的程式中,總是有一系列的語句,Python忠實地按照它們的順序執行它們。如果你想要改變語句流的執行順序,該怎麼辦呢?例如,你想要讓程式做一些決定,根據不同的情況做不同的事情,例如根據時間列印“早上好”或者“晚上好”。
你可能已經猜到了,這是通過控制流程語句實現的。在Python中有三種控制流程語句——if、for和while。
if語句
if語句用來檢驗一個條件, 如果 條件為真,我們運行一塊語句(稱為 if-塊 ), 否則 我們處理另外一塊語句(稱為 else-塊 )。 else 從句是可選的。
使用if語句
例6.1 使用if語句
#!/usr/bin/python
# Filename: if.py
number = 23
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it.' # New block starts here
print "(but you do not win any prizes!)" # New block ends here
elif guess < number:
print 'No, it is a little higher than that' # Another block
# You can do whatever you want in a block ...
else:
print 'No, it is a little lower than that'
# you must have guess > number to reach here
print 'Done'
# This last statement is always executed, after the if statement is executed
(源檔案:code/if.py)
輸出
$ python if.py
Enter an integer : 50
No, it is a little lower than that
Done
$ python if.py
Enter an integer : 22
No, it is a little higher than that
Done
$ python if.py
Enter an integer : 23
Congratulations, you guessed it.
(but you do not win any prizes!)
Done
它如何工作