在 Python 中,if、elif(由 “else and if” 缩写而来)和else语句用于控制程序的执行流程,让程序能够做出判断。
与许多其他编程语言不同,Python 3.9 及更早的版本没有提供正式的 switch 语句,而是用多个elif语句来实现类似的功能。
Python 3.10 引入了一种称为pattern matching的 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搭配使用时,可选的else代码块会在原来的if条件求值为False时执行:
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."