每条if语句的核心都是一个值为True或False的表达式,这种表达式称为条件测试。Python根据条件测试的值为True还是False来决定是否执行if语句中的代码。如果条件测试的值为True,Python就执行紧跟在if语句后面的代码;如果为False,Python就忽略这些代码。
最简单的条件测试检查变量的值是否与特定值相等。
>>> car == 'bmw'
True
>>> car = 'Audi'
>>> car == 'audi'
False
>>> car = 'Audi'
>>> car.lower() == 'audi'
True
>>> car
'Audi'
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
>>> age = 18
>>> age == 18
True
>>> age = 19
>>> age < 21
True
>>> age <= 21
True
>>> age > 21
False
>>> age >= 21
False
>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 and age_1 >= 21 // 或 (age_0 >= 21) and (age_1 >= 21)
False
>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 or age_1 >= 21
True
>>> requested_toppings = ['mushrooms', 'onions', 'pineapple']
>>> 'mushrooms' in requested_toppings
True
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(f"{user.title()}, you can post a response if you wish.")
game_active = True
can_edit = False
age = 19
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
当需要在条件测试通过时执行一个操作,在没有通过时执行另一个操作,可使用Python提供的if-else语句。
我们经常需要检查超过两个的情形,为此可使用Python提供的if-elif-else结构。Python只执行if-elif-else结构中的一个代码块。它依次检查每个条件测试,直到遇到通过了的条件测试。
// 例子1:
age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $25.")
else:
print("Your admission cost is $40.")
// 例子2:
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
else:
price = 40
print(f"Your admission cost is ${price}.")
可根据需要使用任意数量的elif代码块。
Python并不要求if-elif结构后面必须有else代码块。在有些情况下,else代码块很有用;而在其他一些情况下,使用一条elif语句来处理特定的情形更清晰。
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
elif age < 65:
price = 40
elif age >= 65:
price = 20
print(f"Your admission cost is ${price}.")
如果只想执行一个代码块,就使用if-elif-else结构;如果要执行多个代码块,就使用一系列独立的if语句。
在运行for循环前确定列表是否为空很重要。
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print(f"Adding {requested_topping}.")
print("\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?")