学习阶梯
《Python编程:从入门到实践》
第5章 if语句
- 一个简单的示例
toppings.py
#遍历列表,并以首字母大写的方式打印其中的汽车名,但对于汽车名'bmw',以全大写的方式打印
cars = ['bmw', 'audi', 'toyota', 'subaru']
for car in cars:
if car =='bmw':
print(car.upper())
else:
print(car.title())
- 条件测试
每条if语句的核心都是一个值为True或False的表达式,这种表达式被称为条件测试。Python
根据条件测试的值为True还是False来决定是否执行if语句中的代码。
- 检查是否相等
一个等号是陈述;两个等号是发问
car='bmw'
print(car=='bmw')
car='audi'
print(car=='bmw')
- 检查是否相等时考虑大小写
car='bmw'
print(car=='bmw')
car='audi'
print(car=='bmw')
car='Audi'
print(car=='audi')
print(car.lower()=='audi')
- 检查是否不相等
要判断两个值是否不等,可结合使用惊叹号和等号(=),其中的惊叹号表示不
requested_topping='mushrooms'
if requested_topping!='anchovies':
print("Hold the anchovies!")
- 比较数字
age=18
print(age==18)
answer=17
if answer !=42:
print("That is not the correct answer. Please try again!")
age=19
print(age<21)
print(age<=21)
print(age>21)
print(age>=21)
- 检查多个条件
使用关键字and和or,有时候需要在两个条件都为True时才执行相应的操作,而有时候只要求一个条件为True时就执行相应的操作。
#使用and检查多个条件
age_0=22
age_1=18
print(age_0>=21 and age_1>=21)
age_1=21
print(age_0>=21 and age_1>=21)
print((age_0>=21)and(age_1>=21))#加括号可以增强可读性,但不是必须这样做
#使用or检查多个条件
age_0 = 22
age_1 = 18
print(age_0 >= 21 or age_1 >= 21)
age_0 = 18
print(age_0 >= 21 or age_1 >= 21)
- 检查特定值是否包含在列表中
要判断特定的值是否已包含在列表中,可使用关键字in
requested_toppings=['mushrooms','onions','pineapple']
print('mushrooms' in requested_toppings)
print('pepperoni' in requested_toppings)
- 检查特定值是否不包含在列表中
确定特定的值是否未包含在列表可使用关键字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.")
- 布尔表达式
布尔值通常用于记录条件
game_active=True
can_edit=False
print(game_active)
print(can_edit)
练习
#5-1 条件测试:编写一系列条件测试;将每个测试以及你对其结果的预测和实际结果都打印出来。你编写的代码应类似于下面这样:
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nIs car == 'audi'? I predict False.")
print(car == 'audi')
##详细研究实际结果,直到你明白了它为何为 True 或 False。
##创建至少 10 个测试,且其中结果分别为 True 和 False 的测试都至少有 5 个。
number=5
print("Is number==5 ? I predict True." + "In fact, it is " + str(number == 5))
print("Is number!=5 ? I predict False." + "In fact, it is " + str(number != 5))
print("Is number<9 ? I predict True." + "In fact, it is " + str(number < 9))
print("Is number<=9 ? I predict True." + "In fact, it is " + str(number <= 9))
print("Is number<3 ? I predict False." + "In fact, it is " + str(number < 3))
print("Is number<=3 ? I predict False." + "In fact, it is " + str(number <= 3))
print("Is number>3 ? I predict True." + "In fact, it is " + str(number > 3))
print("Is number>=3 ? I predict True." + "In fact, it is " + str(number >= 3))
print("Is number>9 ? I predict False." + "In fact, it is " + str(number > 9))
print("Is number>=9 ? I predict False." + "In fact, it is " + str(number >= 9))
#5-2 更多的条件测试:你并非只能创建 10 个测试。如果你想尝试做更多的比较,可再编写一些测试,并将它们加入到 conditional_tests.py 中。对于下面列出的各种测试,至少编写一个结果为 True 和 False 的测试。
string_0='test'
string_1='Test'
## 检查两个字符串相等和不等。
print(string_0 == string_1)
print(string_0 != string_1)
## 使用函数 lower()的测试。
print(string_0 == (string_1.lower()))
print(string_0 != (string_1.lower()))
## 检查两个数字相等、不等、大于、小于、大于等于和小于等于。
number_0=3
number_1=6
print(number_0 == number_1)
print(number_0 != number_1)
print(number_0 > number_1)
print(number_0 < number_1)
print(number_0 >= number_1)
print(number_0 <= number_1)
## 使用关键字 and 和 or 的测试。
print((number_0 > 5) and (number_1 > 5))
print((number_0 > 5) and (number_1 < 5))
print((number_0 > 5) or (number_1 > 5))
print((number_0 > 5) or (number_1 < 5))
## 测试特定的值是否包含在列表中。
foods=['milk','orange']
food_0 = 'orange'
if food_0 in foods:
print("Yes!")
else:
print("No!")
## 测试特定的值是否未包含在列表中。
food_1 = 'meat'
if food_1 not in foods:
print("Yes!")
else:
print("No!")
- if语句
voting.py
- 简单的if语句
age=19
if age>=18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
- if-else语句
经常需要在条件测试通过了时执行一个操作,并在没有通过时执行另一个操作
#age=19
age=17
if age>=18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
#if-else语句
else:
print("Sorry,you are too young to vote.")
print("Please register to vote as soon as you turn 18!")
- if-elif-else语句
limit_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.") """
if age < 4:
price=0
elif age < 18:
price=5
else:
price=10
print("Your admission cost is $"+str(price)+".")
- 使用多个elif代码块
if age < 4:
price = 0
elif age < 18:
price = 5
elif limit_age<65:
price = 10
else:
price =5
print("Your admission cost is $" + str(price) + ".")
- 省略else代码块
Python并不要求if-elif结构后面必须有else代码块
if age < 4:
price = 0
elif age < 18:
price = 5
elif limit_age < 65:
price = 10
elif limit_age>=65:
price =5
print("Your admission cost is $" + str(price) + ".")
else是一条包罗万象的语句,只要不满足任何if或elif中的条件测试,其中的代码就会执行,这可能会引入无效甚至恶意的数据。
如果知道最终要测试的条件,应考虑使用一个elif代码块来代替else代码块。这样,你就可以肯定,仅当满足相应的条件时,你的代码才会执行。
- 测试多个条件
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!")
如果只想执行一个代码块,就使用if-elif-else结构;
如果要运行多个代码块,就使用一系列独立的if语句。
练习
#5-3 外星人颜色#1:假设在游戏中刚射杀了一个外星人,请创建一个名为alien_color 的变量,并将其设置为'green'、'yellow'或'red'。
##编写一条 if 语句,检查外星人是否是绿色的;如果是,就打印一条消息,指出玩家获得了 5 个点。
##编写这个程序的两个版本,在一个版本中上述测试通过了,而在另一个版本中未通过(未通过测试时没有输出)。
alien_color='green'
if alien_color=='green':
print("Congratulations, you gains 5 points!")
if alien_color=='yellow':
print("Congratulations, you gains 5 points!")
#5-4 外星人颜色#2:像练习 5-3 那样设置外星人的颜色,并编写一个 if-else 结构。
##如果外星人是绿色的,就打印一条消息,指出玩家因射杀该外星人获得了5个点。
##如果外星人不是绿色的,就打印一条消息,指出玩家获得了 10 个点。
##编写这个程序的两个版本,在一个版本中执行 if 代码块,而在另一个版本中执行 else 代码块。
alien_color = 'green'
#alien_color='yellow'
if alien_color=='green':
print("Congratulations, you gains 5 points for shooting green aliens!")
else:
print("Congratulations, you gains 10 points!")
#5-5 外星人颜色#3:将练习 5-4 中的 if-else 结构改为 if-elif-else 结构。
##如果外星人是绿色的,就打印一条消息,指出玩家获得了 5 个点。
## 如果外星人是黄色的,就打印一条消息,指出玩家获得了 10 个点。
## 如果外星人是红色的,就打印一条消息,指出玩家获得了 15 个点。
## 编写这个程序的三个版本,它们分别在外星人为绿色、黄色和红色时打印一条消息。
alien_color = 'green'
#alien_color='yellow'
#alien_color='red'
if alien_color=='green':
print("Congratulations, you gains 5 points for shooting green aliens!")
elif alien_color=='yellow':
print("Congratulations, you gains 10 points for shooting yellow aliens!")
elif alien_color=='red':
print("Congratulations, you gains 15 ponts for shooting red aliens!")
#5-6 人生的不同阶段:设置变量 age 的值,再编写一个 if-elif-else 结构,根据 age的值判断处于人生的哪个阶段。
## 如果一个人的年龄小于 2 岁,就打印一条消息,指出他是婴儿。
## 如果一个人的年龄为 2(含)~4 岁,就打印一条消息,指出他正蹒跚学步。
## 如果一个人的年龄为 4(含)~13 岁,就打印一条消息,指出他是儿童。
## 如果一个人的年龄为 13(含)~20 岁,就打印一条消息,指出他是青少年。
## 如果一个人的年龄为 20(含)~65 岁,就打印一条消息,指出他是成年人。
## 如果一个人的年龄超过 65(含)岁,就打印一条消息,指出他是老年人。
age=12
if age<2:
print("You're still a baby!")
elif age<4:
print("You're a toddler!")
elif age<13:
print("You're a child!")
elif age<20:
print("You're a teenager!")
elif age<65:
print("You're an adult!")
elif age>=65:
print("You're an old man!")
#5-7 喜欢的水果:创建一个列表,其中包含你喜欢的水果,再编写一系列独立的 if语句,检查列表中是否包含特定的水果。
## 将该列表命名为 favorite_fruits,并在其中包含三种水果。
## 编写 5 条 if 语句,每条都检查某种水果是否包含在列表中,如果包含在列表中,就打印一条消息,如“You really like bananas!”。
fruits=['apple','orange','banana','strawberry','grape']
favorite_fruits=['banana','strawberry','grape']
if 'apple' in favorite_fruits:
print("You really like apples!")
if 'orange' in favorite_fruits:
print("You really like oranges!")
if 'banana' in favorite_fruits:
print("You really like bananas!")
if 'strawberry' in favorite_fruits:
print("You really like strawberries!")
if 'grape' in favorite_fruits:
print("You really like grapes!")
- 使用if语句处理列表
pizzas.py
- 检查特殊元素
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!")
- 确定列表不是空的
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?")
在if语句中将列表名用在条件表达式中时,Python将在列表至少包含一个元素时返回True,并在列表为空时返回False。
- 使用多个列表
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!")
练习
#5-8 以特殊方式跟管理员打招呼:创建一个至少包含 5 个用户名的列表,且其中一个用户名为'admin'。想象你要编写代码,在每位用户登录网站后都打印一条问候消息。遍历用户名列表,并向每位用户打印一条问候消息。
##如果用户名为'admin',就打印一条特殊的问候消息,如“Hello admin, would you like to see a status report?”。
## 否则,打印一条普通的问候消息,如“Hello Eric, thank you for logging in again”。
user_names=['admin','jade','marry','john','doris','coral']
for user_name in user_names:
if user_name=='admin':
print("Hello admin, would you like to see a status report?")
else:
print("Hello "+user_name+" , thank you for logging in again.")
#5-9 处理没有用户的情形:在为完成练习 5-8 编写的程序中,添加一条 if 语句,检查用户名列表是否为空。
## 如果为空,就打印消息“We need to find some users!”。
## 删除列表中的所有用户名,确定将打印正确的消息。
user_names = []
if user_names:
for user_name in user_names:
if user_name == 'admin':
print("Hello admin, would you like to see a status report?")
else:
print("Hello " + user_name + " , thank you for logging in again.")
else:
print("We need to find some users!")
#5-10 检查用户名:按下面的说明编写一个程序,模拟网站确保每位用户的用户名都独一无二的方式。
## 创建一个至少包含 5 个用户名的列表,并将其命名为 current_users。
## 再创建一个包含 5 个用户名的列表,将其命名为 new_users,并确保其中有一两个用户名也包含在列表 current_users 中。
## 遍历列表 new_users,对于其中的每个用户名,都检查它是否已被使用。如果是这样,就打印一条消息,指出需要输入别的用户名;否则,打印一条消息,指出这个用户名未被使用。
## 确保比较时不区分大消息;换句话说,如果用户名'John'已被使用,应拒绝用户名'JOHN'。
current_users = ['jade', 'marry', 'john', 'doris', 'coral']
new_users = ['jack', 'marry', 'peter', 'doris', 'nick']
for user in new_users:
if user in current_users:
print(user.title()+" and "+user.upper()+" are already in use.Please enter another user name.")
else:
print(user.title()+" is not in use.")
# 5-11 序数:序数表示位置,如 1st 和 2nd。大多数序数都以 th 结尾,只有 1、2 和 3例外。
## 在一个列表中存储数字 1~9。
## 遍历这个列表。
## 在循环中使用一个 if-elif-else 结构,以打印每个数字对应的序数。输出内容应为 1st、2nd、3rd、4th、5th、6th、7th、8th 和 9th,但每个序数都独占一行。
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in numbers:
if number==1:
print(str(number)+"st")
elif number==2:
print(str(number)+"nd")
elif number==3:
print(str(number)+"rd")
else:
print(str(number) + "th")
print("All output completed!")
- 设置if语句的格式
在诸如==、>=和<=等比较运算符两边各添加一个空格,例如,if age < 4:要比if age<4:好。
这样的空格不会影响Python对代码的解读,而只是让代码阅读起来更容易。