在 Python 中,if、elif(為「else and if」的縮寫)與 else 敘述用來控制執行流程,讓程式做出判斷。
和許多其他程式語言不同,Python 3.9 及更早的版本並沒有正式的 case-switch 敘述,而是改用多個elif敘述來達到類似的目的。
Python 3.10 引入了稱為pattern matching的變體 case-switch 敘述,我們會在另一個概念中另外介紹。
條件敘述使用的運算式必須得出True或False,無論是直接回傳bool,或是評估其為「truthy」或「falsy」。
x = 10
y = 5
# The comparison '>' returns the bool 'True',
# so the statement is printed.
if x > y:
print("x is greater than y")
...
>>> x is greater than y
搭配if使用時,當原本的if條件評估為False,可選的else程式區塊就會執行:
x = 5
y = 10
# The comparison '>' here returns the bool False,
# so the 'else' block is executed instead of the 'if' block.
if x > y:
print("x is greater than y")
else:
print("y is greater than x")
...
>>> y is greater than x
elif可以進行多次評估、產生多個分支。
x = 5
y = 10
z = 20
# The elif statement allows for the checking of more conditions.
if x > y > z:
print("x is greater than y and z")
elif y > x > z:
print("y is greater than x and z")
else:
print("z is greater than x and y")
...
>>> z is greater than x and y
>>> def classic_fizzbuzz(number):
... if number % 3 == 0 and number % 5 == 0:
... say = 'FizzBuzz!'
... elif number % 5 == 0:
... say = 'Buzz!'
... elif number % 3 == 0:
... say = 'Fizz!'
... else:
... say = str(number)
...
... return say
>>> classic_fizzbuzz(15)
'FizzBuzz!'
>>> classic_fizzbuzz(13)
'13'
另一種做法是,把上面的例子改寫成只使用帶有returns的if敘述。
不過,這樣改寫可能會讓人看不出這些條件其實是互斥的,日後也可能因此產生 bug 或維護上的問題。
>>> def classic_fizzbuzz(number):
... if number % 3 == 0 and number % 5 == 0:
... return 'FizzBuzz!'
... if number % 5 == 0:
... return 'Buzz!'
... if number % 3 == 0:
... return 'Fizz!'
...
... return str(number)
>>> classic_fizzbuzz(15)
'FizzBuzz!'
>>> classic_fizzbuzz(13)
'13'
條件敘述也可以巢狀使用。
>>> def driving_status(driver_age, test_score):
... if test_score >= 80:
... if 18 > driver_age >= 16:
... status = "Student driver, needs supervision."
... elif driver_age == 18:
... status = "Permitted driver, on probation."
... elif driver_age > 18:
... status = "Fully licensed driver."
... else:
... status = "Unlicensed!"
...
... return status
>>> driving_status(63, 78)
'Unlicensed!'
>>> driving_status(16, 81)
'Student driver, needs supervision.'
>>> driving_status(23, 80)
'Fully licensed driver.'
Python 雖然沒有專門的?三元運算子,但可以寫出單行的conditional expressions。
形式為<value if True> if <conditional test> else <value if False>。
由於這類運算式可能变得不容易閱讀,建議只有在能縮短程式碼並提升可讀性時,才使用這種單行寫法。
>>> def just_the_buzz(number):
... return 'Buzz!' if number % 5 == 0 else str(number)
>>> just_the_buzz(15)
'Buzz!'
>>> just_the_buzz(7)
'7'
在 Python 中,任何物件都可以測試其真值,因此可以用在條件、比較或布林運算中。
以這種方式評估的物件會被視為「truthy」或「falsy」,並用在boolean context中。
>>> def truthy_test(thing):
... if thing:
... print('This is Truthy.')
... else:
... print("Nope. It's Falsy.")
# Empty container objects are considered Falsy.
>>> truthy_test([])
"Nope. It's Falsy."
>>> truthy_test(['bear', 'pig', 'giraffe'])
'This is Truthy.'
# Empty strings are considered Falsy.
>>> truthy_test('')
"Nope. It's Falsy."
>>> truthy_test('yes')
'This is Truthy.'
# 0 is also considered Falsy.
>>> truthy_test(0)
"Nope. It's Falsy."