第5章 if语句
5.1 简单示例
假设你有一个汽车列表,并想将其中每辆汽车的名称打印出来。对于大多数汽车,都应以首字母大写的方式打印其名称,但对于汽车名’bmw’,应以全大写的方式打印。
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
这个示例中的循环首先检查当前的汽车名是否是’bmw’。如果是,就以全大写的方式打印它;否则就以首字母大写的方式打印:
Audi
BMW
Subaru
Toyota
5.2 条件测试
每条if语句的核心都是一个值为True或False的表达式,这种表达式被称为条件测试。Python根据条件测试的值为True还是False来决定是否执行if语句中的代码。如果条件测试的值为True,Python就执行紧跟在if语句后面的代码;如果为False,Python就忽略这些代码。
5.2.1 检查是否相等
大多数条件测试都将一个变量的当前值同特定值进行比较。最简单的条件测试检查变量的值是否与特定值相等:
>>> car = 'bmw'
>>> car == 'bmw'
True
如果变量car的值不是’bmw’,上述测试将返回False:
>>> car = 'audi'
>>> car == 'bmw'
False
5.2.2 检查是否相等时不考虑大小写
在Python中检查是否相等时区分大小写,例如,两个大小写不同的值会被视为不相等:
>>> car = 'Audi'
>>> car == 'audi'
False
如果大小写很重要,这种行为有其优点。但如果大小写无关紧要,而只想检查变量的值,可将变量的值转换为小写,再进行比较:
>>> car = 'Audi'
>>> car.lower() == 'audi'
True
无论值’Audi’的大小写如何,上述测试都将返回True,因为该测试不区分大小写。函数lower()不会修改存储在变量car中的值,因此进行这样的比较时不会影响原来的变量:
>>> car = 'Audi'
>>> car.lower() == 'audi'
True
>>> car
'Audi'
5.2.3 检查是否不相等
要判断两个值是否不等,可结合使用惊叹号和等号(!=),其中的惊叹号表示不,在很多编程语言中都如此。
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
Hold the anchovies!
5.2.4 比较数字
>>> age = 18
>>> age == 18
True
你还可以检查两个数字是否不等:
answer = 17
if answer != 42:
print("That is not the correct answer. Please try again!")
answer(17)不是42,条件得到满足,因此缩进的代码块得以执行:
That is not the correct answer. Please try again!
条件语句中可包含各种数学比较,如小于、小于等于、大于、大于等于:
>>> age = 19
>>> age < 21
True
>>> age <= 21
True
>>> age > 21
False
>>> age >= 21
False
5.2.5 检查多个条件
你可能想同时检查多个条件,例如,有时候你需要在两个条件都为True时才执行相应的操作,而有时候你只要求一个条件为True时就执行相应的操作。在这些情况下,关键字and和or可助你一臂之力。
1. 使用and检查多个条件
要检查是否两个条件都为True,可使用关键字and将两个条件测试合而为一;如果每个测试都通过了,整个表达式就为True;如果至少有一个测试没有通过,整个表达式就为False。
>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 and age_1 >= 21
False
>>> age_1 = 22
>>> age_0 >= 21 and age_1 >= 21
True
为改善可读性,可将每个测试都分别放在一对括号内,但并非必须这样做。如果你使用括号,测试将类似于下面这样:
(age_0 >= 21) and (age_1 >= 21)
2. 使用or检查多个条件
关键字or也能够让你检查多个条件,但只要至少有一个条件满足,就能通过整个测试。仅当两个测试都没有通过时,使用or的表达式才为False。
>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 or age_1 >= 21
True
>>> age_0 = 18
>>> age_0 >= 21 or age_1 >= 21
False
5.2.6 检查特定值是否包含在列表中
有时候,执行操作前必须检查列表是否包含特定的值。要判断特定的值是否已包含在列表中,可使用关键字in。
>>> requested_toppings = ['mushrooms', 'onions', 'pineapple']
>>> 'mushrooms' in requested_toppings
True
>>> 'pepperoni' in requested_toppings
False
5.2.7 检查特定值是否不包含在列表中
还有些时候,确定特定的值未包含在列表中很重要;在这种情况下,可使用关键字not in。
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(user.title() + ", you can post a response if you wish.")
用户’marie’未包含在列表banned_users中,因此她将看到一条邀请她发表评论的消息:
Marie, you can post a response if you wish.
5.2.8 布尔表达式
随着你对编程的了解越来越深入,将遇到术语布尔表达式,它不过是条件测试的别名。与条件表达式一样,布尔表达式的结果要么为True,要么为False。
布尔值通常用于记录条件:
game_active = True
can_edit = False
5.3 if 语句
理解条件测试后,就可以开始编写if语句了。if语句有很多种,选择使用哪种取决于要测试的条件数。
5.3.1 简单的 if 语句
最简单的if语句只有一个测试和一个操作:
if conditional_test:
do something
5.3.2 if-else 语句
经常需要在条件测试通过了时执行一个操作,并在没有通过时执行另一个操作;在这种情况下,可使用Python提供的if-else语句。if-else语句块类似于简单的if语句,但其中的else语句让你能够指定条件测试未通过时要执行的操作。
age = 17
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else:
print("Sorry, you are too young to vote.")
print("Please register to vote as soon as you turn 18!")
如果条件测试通过了,就执行第一个缩进的print语句块;如果测试结果为False,就执行else代码块。
Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!
5.3.3 if-elif-else 结构
经常需要检查超过两个的情形,为此可使用Python提供的if-elif-else结构。Python只执行if-elif-else结构中的一个代码块,它依次检查每个条件测试,直到遇到通过了的条件测试。测试通过后,Python将执行紧跟在它后面的代码,并跳过余下的测试。
age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.")
在这个示例中,测试的结果为False,因此不执行其代码块。然而,第二个测试的结果为True(12小于18),因此将执行其代码块。输出为一个句子,向用户指出了门票价格:
Your admission cost is $5.
为让代码更简洁,可不在if-elif-else代码块中打印门票价格,而只在其中设置门票价格,并在它后面添加一条简单的print语句:
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
else:
price = 10
print("Your admission cost is $" + str(price) + ".")
5.3.4 使用多个 elif 代码块
可根据需要使用任意数量的elif代码块:
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
else:
price = 5
print("Your admission cost is $" + str(price) + ".")
5.3.5 省略 else 代码块
Python并不要求if-elif结构后面必须有else代码块。在有些情况下,else代码块很有用;而在其他一些情况下,使用一条elif语句来处理特定的情形更清晰:
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
elif age >= 65:
price = 5
print("Your admission cost is $" + str(price) + ".")
5.3.6 测试多个条件
if-elif-else结构功能强大,但仅适合用于只有一个条件满足的情况:遇到通过了的测试后,Python就跳过余下的测试。这种行为很好,效率很高,让你能够测试一个特定的条件。
然而,有时候必须检查你关心的所有条件。在这种情况下,应使用一系列不包含elif和else代码块的简单if语句。在可能有多个条件为True,且你需要在每个条件为True时都采取相应措施时,适合使用这种方法。
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!")
在这个示例中,会检查每个条件,因此将在比萨中添加蘑菇并多加芝士:
Adding mushrooms.
Adding extra cheese.
Finished making your pizza!
如果像下面这样转而使用if-elif-else结构,代码将不能正确地运行,因为有一个测试通过后,就会跳过余下的测试:
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
elif 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
elif 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!")
其结果是,将添加顾客点的第一种配料,但不会添加其他的配料:
Adding mushrooms.
Finished making your pizza!
总之,如果你只想执行一个代码块,就使用if-elif-else结构;如果要运行多个代码块,就使用一系列独立的if语句。
5.4 使用 if 语句处理列表
通过结合使用if语句和列表,可完成一些有趣的任务:对列表中特定的值做特殊处理;高效地管理不断变化的情形,
5.4.1 检查特殊元素
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
输出很简单,因为上述代码不过是一个简单的for循环:
Adding mushrooms.
Adding green peppers.
Adding extra cheese.
Finished making your pizza!
然而,如果比萨店的青椒用完了,该如何处理呢?为妥善地处理这种情况,可在for循环中包含一条if语句:
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Sorry, we are out of green peppers right now.")
else:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
输出表明,妥善地处理了顾客点的每种配料:
Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.
Finished making your pizza!
5.4.2 确定列表不是空的
到目前为止,对于处理的每个列表都做了一个简单的假设,即假设它们都至少包含一个元素。我们马上就要让用户来提供存储在列表中的信息,因此不能再假设循环运行时列表不是空的。有鉴于此,在运行for循环前确定列表是否为空很重要。
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?")
在这里,这个列表为空,因此输出如下——询问顾客是否确实要点普通比萨:
Are you sure you want a plain pizza?
如果这个列表不为空,将显示在比萨中添加的各种配料的输出。
5.4.3 使用多个列表
available_toppings = ['mushrooms', 'olives', 'green peppers',
'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding " + requested_topping + ".")
else:
print("Sorry, we don't have " + requested_topping + ".")
print("\nFinished making your pizza!")
这些代码的输出整洁而详实:
Adding mushrooms.
Sorry, we don't have french fries.
Adding extra cheese.
Finished making your pizza!
5.5 设置 if 语句的格式
本章的每个示例都展示了良好的格式设置习惯。在条件测试的格式设置方面,PEP 8提供的唯一建议是,在诸如==、>=和<=等比较运算符两边各添加一个空格,例如,if age < 4:要比if age<4:好。这样的空格不会影响Python对代码的解读,而只是让代码阅读起来更容易。
5.6 小结
在本章中,你学习了如何编写结果要么为Ture要么为False的条件测试。你学习了如何编写简单的if语句、if-else语句和if-elif-else结构。在程序中,你使用了这些结构来测试特定的条件,以确定这些条件是否满足。你学习了如何在利用高效的for循环的同时,以不同于其他元素的方式对特定的列表元素进行处理。你还再次学习了Python就代码格式方面提出的建议,这可确保即便你编写的程序越来越复杂,其代码依然易于阅读和理解。