第5章 if 语句
5.1 一个简单示例
1 cars = ['audi', 'bmw', 'subaru', 'toyota'] 2 for car in cars: 3 if car == 'bmw': 4 print(car.upper()) 5 else: 6 print(car.title()) 7 """ 8 Audi 9 BMW 10 Subaru 11 Toyota 12 """
①用 if 语句来正确地处理特殊情形。
②检查当前的汽车名是否是 'bmw' ,如行3。如果是,就以全大写的方式打印它,如行4;否则就以首字母大写的方式打印,如行6。
5.2 条件测试
每条 if 语句的核心都是一个值为 True 或 False 的表达式,这种表达式被称为条件测试。
Python根据条件测试的值为 True 还是 False 来决定是否执行 if 语句中的代码。
如果条件测试的值为 True ,Python就执行紧跟在 if 语句后面的代码;如果为 False , Python 就忽略这些代码。
-
5.2.1 检查是否相等
1 car = 'bmw' 2 print(car == 'bmw') 3 # True
①相等运算符在它两边的值相等时返回 True ,否则返回 False 。如行2
②“=”是赋值符号,“==”是相等运算符。
-
5.2.2 检查是否相等时不考虑大小写
1 car = 'Audi' 2 print(car == 'audi') 3 print(car.lower() == 'audi') 4 print(car) 5 """ 6 False 7 True 8 Audi 9 """
①在Python中检查是否相等时区分大小写。
②但如果大小写无关紧要,而只想检查变量的值,可将变量的值转换为小写,再进行比较。
③lower()方法没有影响存储在变量中的值。
-
5.2.3 检查是否不相等
1 requested_topping = 'mushrooms' 2 if requested_topping != 'anchovies': 3 print("Hold the anchovies!")
①要判断两个值是否不等,可结合使用惊叹号和等号( != ),其中的惊叹号表示不。如行2
-
5.2.4 比较数字
1 age = 18 2 print(age == 18) 3 answer = 17 4 if answer != 42: 5 print("That is not the correct answer. Please try again!") 6 age = 19 7 print(age < 21) 8 print(age <= 21) 9 print(age > 21) 10 print(age >= 21) 11 """ 12 True 13 That is not the correct answer. Please try again! 14 True 15 True 16 False 17 False 18 """
①“==”可以检查两个数字是否相等。如行2
②“!=”可以检查两个数字是否不等。如行4
③条件语句中可包含各种数学比较,如小于、小于等于、大于、大于等于。如行7-10
-
5.2.5 检查多个条件
你可能想同时检查多个条件,例如,有时候你需要在两个条件都为 True 时才执行相应的操作,而有时候你只要求一个条件为 True 时就执行相应的操作。在这些情况下,关键字 and 和 or 可助你。
1. 使用 and 检查多个条件
1 age_0 = 22 2 age_1 = 18 3 print(age_0 >= 21 and age_1 >= 21) 4 age_1 = 22 5 print(age_0 >= 21 and age_1 >= 21) 6 """ 7 False 8 True 9 """
①要检查是否两个条件都为 True ,可使用关键字 and 将两个条件测试合而为一;如果每个测试都通过了,整个表达式就为 True ;如果至少有一个测试没有通过,整个表达式就为 False 。如行3、5
②为改善可读性,可将每个测试都分别放在一对括号内。
1 (age_0 >= 21) and (age_1 >= 21)
2. 使用 or 检查多个条件
1 age_0 = 22 2 age_1 = 18 3 print(age_0 >= 21 or age_1 >= 21) 4 age_0 = 18 5 print(age_0 >= 21 or age_1 >= 21)
①关键字 or 也能够让你检查多个条件,但只要至少有一个条件满足,就能通过整个测试。如行3
②仅当两个测试都没有通过时,使用 or 的表达式才为 False 。如行5
-
5.2.6 检查特定值是否包含在列表中
1 requested_topping = ['mushrooms', 'onion', 'pineapple'] 2 print('mushrooms' in requested_topping) 3 # True 4 print('pepperoni' in requested_topping) 5 # False
①可使用关键字 in ,来判断特定的值是否已包含在列表中。如行2、4
-
5.2.7 检查特定值是否不包含在列表中
1 banned_users = ['andrew', 'carolina', 'david'] 2 user = 'marie' 3 if user not in banned_users: 4 print(user.title() + ", you can post a response if you wish.") 5 # Marie, you can post a response if you wish.
①可使用关键字 not in ,确定特定的值未包含在列表中。如行3
-
5.2.8 布尔表达式
1 #布尔表达式 2 game_active = True 3 can_edit = False
①布尔表达式,它不过是条件测试的别名。与条件表达式一样,布尔表达式的结果要么为 True ,要么为 False 。
1 #习题1 2 ball = 'basketball' 3 print("Is ball == 'badminton'? I predict True.") 4 print(ball == 'badminton') 5 print("Is ball == 'basketball'? I predict False.") 6 print(ball == 'basketball') 7 8 flower = 'rose' 9 print("Is flower == 'rose'? I predict True.") 10 print(flower == 'rose') 11 print("Is flower == 'lily'? I predict False.") 12 print(flower == 'lily') 13 14 food = 'chocolate' 15 print("Is food == 'chocolate'? I predict True.") 16 print(food == 'chocolate') 17 print("Is food == 'sugar'? I predict False.") 18 print(food == 'sugar') 19 20 exercise = 'run' 21 print("Is exercise == 'walk'? I predict True.") 22 print(exercise == 'walk') 23 print("Is exercise == 'run'? I predict False.") 24 print(exercise == 'run') 25 26 work = 'programmer' 27 print("Is work == 'accountant'? I predict True.") 28 print(work == 'accountant') 29 print("Is work == 'programmer'? I predict False.") 30 print(work == 'programmer') 31 """ 32 Is ball == 'badminton'? I predict True. 33 False 34 Is ball == 'basketball'? I predict False. 35 True 36 Is flower == 'rose'? I predict True. 37 True 38 Is flower == 'lily'? I predict False. 39 False 40 Is food == 'chocolate'? I predict True. 41 True 42 Is food == 'sugar'? I predict False. 43 False 44 Is exercise == 'walk'? I predict True. 45 False 46 Is exercise == 'run'? I predict False. 47 True 48 Is work == 'accountant'? I predict True. 49 False 50 Is work == 'programmer'? I predict False. 51 True 52 """ 53 #习题2 54 exercise = 'run' 55 print(exercise == 'programmer') 56 print(exercise != 'programmer') 57 exercise = 'Run' 58 print(exercise == 'run') 59 print(exercise.lower() == 'run') 60 """ 61 False 62 True 63 False 64 True 65 """ 66 car_number = 3 67 print(car_number > 4) 68 print(car_number < 4) 69 print(car_number >= 4) 70 print(car_number <= 4) 71 """ 72 False 73 True 74 False 75 True 76 """ 77 car_number = 5 78 aircraft = 3 79 print(car_number > 6 and aircraft < 4) 80 print(car_number >6 or aircraft < 4) 81 """ 82 False 83 True 84 """ 85 exercise = ['run', 'walk', 'swim', 'ping-pong', 'basketball'] 86 print('swim' in exercise) 87 print('swim' not in exercise) 88 """ 89 True 90 False 91 """
5.3 if 语句
-
5.3.1 简单的 if 语句
1 age = 19 2 if age >= 18: 3 print("You are old enough to vote!") 4 print("Have you registered to vote yet?") 5 """ 6 You are old enough to vote! 7 Have you registered to vote yet? 8 """
①最简单的 if 语句只有一个测试和一个操作:
1 if conditional_test: 2 do something
在第1行中,可包含任何条件测试,而在紧跟在测试后面的缩进代码块中,可执行任何操作。如果条件测试的结果为 True ,Python就会执行紧跟在 if 语句后面的代码;否则Python将忽略这些代码。如行2-4
-
5.3.2 if-else 语句
1 age = 17 2 if age >= 18: 3 print("You are old enough to vote!") 4 print("Have you registered to vote yet?") 5 else: 6 print("Sorry, you are too young to vote.") 7 print("Please register to vote as soon as you turn 18!") 8 """ 9 Sorry, you are too young to vote. 10 Please register to vote as soon as you turn 18! 11 """
①经常需要在条件测试通过了时执行一个操作,并在没有通过时执行另一个操作;在这种情况下,可使用Python提供的 if-else 语句。 if-else 语句块类似于简单的 if 语句,但其中的 else 语句让你能够指定条件测试未通过时要执行的操作。如行2-7
②if-else 结构非常适合用于要让Python执行两种操作之一的情形。在这种简单的 if-else 结构中,总是会执行两个操作中的一个。
-
5.3.3 if-elif-else 结构
1 age = 12 2 if age <4: 3 print("Your admission cost is $0.") 4 elif age <18: 5 print("Your admission cost is $5.") 6 else: 7 print("Your admission cost is $10.") 8 # Your admission cost is $5. 9 10 age = 12 11 if age < 4: 12 price = 0 13 elif age < 18: 14 price = 5 15 else: 16 price = 10 17 print("Your admission cost is $" + str(price) + ".") 18 # Your admission cost is $5.
①可使用Python提供的 if-elif-else 结构,来检查超过两个的情形。Python只执行if-elif-else 结构中的一个代码块,它依次检查每个条件测试,直到遇到通过了的条件测试。测试通过后,Python将执行紧跟在它后面的代码,并跳过余下的测试。 如行2-7
②代码更简洁,除效率更高外,这些修订后的代码还更容易修改:要调整输出消息的内容,只需修改一条而不是三条 print 语句。如行10-17
-
5.3.4 使用多个 elif 代码块
1 age = 12 2 if age < 4: 3 price = 0 4 elif age < 18: 5 price = 5 6 elif age < 65: 7 price = 10 8 else: 9 price = 5 10 print("Your admission cost is $" + str(price) + ".") 11 # Your admission cost is $5.
①可根据需要使用任意数量的 elif 代码块。如行1-10
-
5.3.5 省略 else 代码块
1 age = 12 2 if age < 4: 3 price = 0 4 elif age < 18: 5 price = 5 6 elif age < 65: 7 price = 10 8 elif age >= 65: 9 price = 5 10 print("Your admission cost is $" + str(price) + ".") 11 # Your admission cost is $5.
①Python并不要求 if-elif 结构后面必须有 else 代码块。在有些情况下, else 代码块很有用;而在其他一些情况下,使用一条 elif 语句来处理特定的情形更清晰。
②else 是一条包罗万象的语句,只要不满足任何 if 或 elif 中的条件测试,其中的代码就会执行,这可能会引入无效甚至恶意的数据。如果知道最终要测试的条件,应考虑使用一个 elif 代码块来代替 else 代码块。这样,你就可以肯定,仅当满足相应的条件时,你的代码才会执行。
-
5.3.6 测试多个条件
1 requested_toppings = ['mushrooms', 'extra cheese'] 2 if 'mushrooms' in requested_toppings: 3 print("Adding mushrooms.") 4 if 'pepperoni' in requested_toppings: 5 print("Adding pepperoni.") 6 if 'extra cheese' in requested_toppings: 7 print("Adding extra cheese.") 8 print(" Finished making your pizza!") 9 """ 10 Adding mushrooms. 11 Adding extra cheese. 12 13 Finished making your pizza! 14 """
①检查你关心的所有条件,使用一系列不包含 elif 和 else代码块的简单 if 语句。在可能有多个条件为 True ,且你需要在每个条件为 True 时都采取相应措施时,适合使用这种方法。
②如果你只想执行一个代码块,就使用 if-elif-else 结构;如果要运行多个代码块,就使用一系列独立的 if 语句。
1 #习题1 2 alien_color = 'green' 3 if alien_color == 'green': 4 print("玩家获得五个点。") 5 # 玩家获得五个点。 6 alien_color = 'red' 7 if alien_color == 'green': 8 print("玩家获得五个点。") 9 10 #习题2 11 alien_color = 'green' 12 if alien_color == 'green': 13 print("玩家射杀了绿色外星人,获得五个点!") 14 else: 15 print("玩家射杀了非绿色外星人,获得十个点!") 16 # 玩家射杀了绿色外星人,获得五个点! 17 alien_color = 'red' 18 if alien_color == 'green': 19 print("玩家射杀了绿色外星人,获得五个点!") 20 else: 21 print("玩家射杀了非绿色外星人,获得十个点!") 22 # 玩家射杀了非绿色外星人,获得十个点! 23 24 #习题3 25 alien_colors = ['green', 'yellow', 'red'] 26 alien_color = 'yellow' 27 if alien_color in alien_colors: 28 if alien_color == 'green': 29 print("玩家射杀了绿色外星人,获得五个点!") 30 elif alien_color == 'yellow': 31 print("玩家射杀了黄色外星人,获得十个点!") 32 else: 33 print("玩家射杀了红色外星人,获得十五个点!") 34 # 玩家射杀了黄色外星人,获得十个点! 35 alien_colors = ['green', 'yellow', 'red'] 36 alien_color = 'green' 37 if alien_color in alien_colors: 38 if alien_color == 'green': 39 print("玩家射杀了绿色外星人,获得五个点!") 40 elif alien_color == 'yellow': 41 print("玩家射杀了黄色外星人,获得十个点!") 42 else: 43 print("玩家射杀了红色外星人,获得十五个点!") 44 # 玩家射杀了绿色外星人,获得五个点! 45 alien_colors = ['green', 'yellow', 'red'] 46 alien_color = 'red' 47 if alien_color in alien_colors: 48 if alien_color == 'green': 49 print("玩家射杀了绿色外星人,获得五个点!") 50 elif alien_color == 'yellow': 51 print("玩家射杀了黄色外星人,获得十个点!") 52 else: 53 print("玩家射杀了红色外星人,获得十五个点!") 54 # 玩家射杀了红色外星人,获得十五个点! 55 56 #习题4 57 age = 22 58 if age < 2: 59 print("他是婴儿!") 60 elif age < 4: 61 print("他正蹒跚学步!") 62 elif age < 13: 63 print("他是儿童!") 64 elif age < 20: 65 print("他是青少年!") 66 elif age < 65: 67 print("他是成年人!") 68 else: 69 print("他是老人!") 70 # 他是成年人! 71 72 #习题5 73 favorit_fruits = ['banana', 'apple', 'pineapple'] 74 if 'banana' in favorit_fruits: 75 print("You really like bananas!") 76 # You really like bananas! 77 if 'apple' in favorit_fruits: 78 print("You really like bananas!") 79 # You really like bananas! 80 if 'pineapple' in favorit_fruits: 81 print("You really like bananas!") 82 # You really like bananas! 83 if 'pear' in favorit_fruits: 84 print("You really like bananas!") 85 if 'cherry' in favorit_fruits: 86 print("You really like bananas!")
5.4 使用 if 语句处理列表
-
5.4.1 检查特殊元素
1 requested_toppings = ['mushrooms', 'green peppers', 'extra cheese'] 2 for requested_topping in requested_toppings: 3 if requested_topping == 'green peppers': 4 print("Sorry, we are out of green peppers right now.") 5 else: 6 print("Adding " + requested_topping + ".") 7 print(" Finished making your pizza!") 8 """ 9 Adding mushrooms. 10 Sorry, we are out of green peppers right now. 11 Adding extra cheese. 12 13 Finished making your pizza! 14 """
①可在 for 循环中包含一条 if 语句,来检查特殊元素。如行2-7
-
5.4.2 确定列表不是空的
1 requested_toppings = [] 2 if requested_toppings: 3 for requested_topping in requested_toppings: 4 print("Adding " + requested_topping + ".") 5 print(" Finished making your pizza!") 6 else: 7 print("Are you sure you want a plain pizza?") 8 # Are you sure you want a plain pizza?
①用if 语句,简单检查,而不是直接执行 for 循环。在 if 语句中将列表名用在条件表达式中时,Python将在列表至少包含一个元素时返回 True ,并在列表为空时返回 False 。如行2-7
-
5.4.3 使用多个列表
1 available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese'] 2 requested_toppings = ['mushrooms', 'french fries', 'extra cheese'] 3 for requested_topping in requested_toppings: 4 if requested_topping in available_toppings:
5 print("Adding " + requested_topping + ".")
6 else:
7 print("Sorry, we don't have " + requested_topping + ".")
8 print(" Finished making your pizza!")
9 """
10 Adding mushrooms.
11 Sorry, we don't have french fries.
12 Adding extra cheese.
13
14 Finished making your pizza!
15 """
①可使用列表和 if 语句来使用多个列表。如行3-8
1 #练习 2 #习题1 3 user_names = ['eric', 'lisa', 'bob', 'bub', 'admin'] 4 for user_name in user_names: 5 if user_name == 'admin': 6 print("Hello " + user_name + ", would you like to see a status report?") 7 else: 8 print("Hello " + user_name + ", thank you for logging in again.") 9 """ 10 Hello eric, thank you for logging in again. 11 Hello lisa, thank you for logging in again. 12 Hello bob, thank you for logging in again. 13 Hello bub, thank you for logging in again. 14 Hello admin, would you like to see a status report? 15 """ 16 17 #习题2 18 user_names1 = ['eric', 'lisa', 'bob', 'bub', 'admin'] 19 user_names = [] 20 if user_names: 21 for user_name in user_names: 22 if user_name == 'admin': 23 print("Hello " + user_name + ", would you like to see a status report?") 24 else: 25 print("Hello " + user_name + ", thank you for logging in again.") 26 else: 27 print("We need to find some users!") 28 29 #习题3 30 current_users = ['eric', 'lisa', 'Bob', 'bub', 'admin'] 31 new_users = ['bob', 'bub', 'ben', 'gill', 'gerry'] 32 for new_user in new_users: 33 if new_user.lower() in [current_user.lower() for current_user in current_users]: 34 print(new_user.title() + " has been registered, please enter another username.") 35 else: 36 print(new_user.title() + " is not used.") 37 """ 38 Bob has been registered, please enter another username. 39 Bub has been registered, please enter another username. 40 Ben is not used. 41 Gill is not used. 42 Gerry is not used. 43 """ 44 45 #习题4 46 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] 47 for number in numbers: 48 if number == 1: 49 print(str(number) + "st") 50 elif number == 2: 51 print(str(number) + "nd") 52 elif number == 3: 53 print(str(number) + "rd") 54 else: 55 print(str(number) + "th") 56 """ 57 1st 58 2nd 59 3rd 60 4th 61 5th 62 6th 63 7th 64 8th 65 9th 66 """
5.5 设置 if 语句的格式
在条件测试的格式设置方面,PEP 8提供的唯一建议是,在诸如 == 、 >= 和 <= 等比较运算符两边各添加一个空格。