【Python编程:从入门到实践】第五章:if 语句
5.1 一个简单的示例
在Python中, if 语句让你能够检查程序的当前状态,并据此采取相应的措施。
Eg:遍历一个列表,并以首字母大写的方式打印其中的汽车名,但对于汽车名 ‘bmw’ ,以全大写的方式打印
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
结果:
Audi
BMW
Subaru
Toyota
5.2 条件测试
- 检查是否相等(==)
>>> car = 'bmw'
>>> car == 'bmw'
True
- 检查是否相等时区分大小写
>>> car = 'Audi'
>>> car == 'audi'
False
只想检查变量的值,可将变量的值转换为小写,再进行比较。函数 lower()不会修改存储在变量 car 中的值
>>> car = 'Audi'
>>> car.lower() == 'audi'
True
- 检查是否不相等(!=)
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
结果:
Hold the anchovies!
- 比较数字
>>> age = 18
>>> age == 18
True
answer = 17
if answer != 42:
print("That is not the correct answer. Please try again!")
各种数学比较,小于、小于等于、大于、大于等于
>>> age = 19
>>> age < 21
True
>>> age <= 21
True
>>> age > 21
False
>>> age >= 21
False
- 检查多个条件(使用and 或or)
检查是否两个条件都为 True ,可使用关键字 and 将两个条件测试合而为一
>>> 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
关键字 or 也能够让你检查多个条件,但只要至少有一个条件满足,就能通过整个测试。
>>> 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
- 检查特定值是否包含在列表中(in)
>>> requested_toppings = ['mushrooms', 'onions', 'pineapple']
>>> 'mushrooms' in requested_toppings
True
>>> 'pepperoni' in requested_toppings
False
- 检查特定值是否不包含在列表中(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
练习
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个。
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nIs car == 'audi'? I predict False.")
print(car == 'audi')
结果:
Is car == 'subaru'? I predict True.
True
Is car == 'audi'? I predict False.
False
5-2 更多的条件测试:你并非只能创建 10个测试。如果你想尝试做更多的比较,可再编写一些测试,并将它们加入到 conditional_tests.py 中。对于下面列出的各种测试,至少编写一个结果为 True 和 False 的测试。
检查两个字符串相等和不等。
使用函数 lower() 的测试。
检查两个数字相等、不等、大于、小于、大于等于和小于等于。
使用关键字 and 和 or 的测试。
测试特定的值是否包含在列表中。
测试特定的值是否未包含在列表中。
user1 = "lily"
user2 = "Lily"
print(user1 == user2)
print(user1 != user2)
print(user1 == user2.lower())
num1 = 2
num2 = 3
print(num1 == num2)
print(num1 != num2)
print(num1 > num2)
print(num1 < num2)
print(num1 >= num2)
print(num1 <= num2)
col1 = 2
col2 = -2
print(col1 > 0 and col2 > 0)
print(col1 > 0 or col2 > 0)
list1 = ['zhao','qian','sun','li','zhou']
name1 = 'zhao'
name2 = 'wu'
if name1 in list1:
print(name1 + " is included in the list.")
if name2 not in list1:
print(name2 + " is not included in the list.")
结果:
False
True
True
False
True
False
True
False
True
False
True
zhao is included in the list.
wu is not included in the list.
5.3 if 语句
- 简单的if语句
age = 19
if age >= 18:
print("You are old enough to vote!")
结果:
You are old enough to vote!
- 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!")
结果:
Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!
- if-elif-else 结构
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.")
结果:
Your admission cost is $5.
- 使用多个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) + ".")
结果:
Your admission cost is $5.
- 省略else代码块
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) + ".")
结果:
Your admission cost is $5.
- 测试多个条件
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!
练习
5-3 外星人颜色#1:假设在游戏中刚射杀了一个外星人,请创建一个名为alien_color 的变量,并将其设置为 ‘green’ 、 ‘yellow’ 或 ‘red’ 。
编写一条 if 语句,检查外星人是否是绿色的;如果是,就打印一条消息,指出玩家获得了 5个点。
编写这个程序的两个版本,在一个版本中上述测试通过了,而在另一个版本中未通过(未通过测试时没有输出)。
alien_colors = ['green','yellow','red']
#Q1
print("Q1")
alien_color = 'green'
if alien_color == 'green':
print('you have won five point')
#Q2
print("Q2")
alien_color = 'red'
if alien_color == 'green':
print('you have won five point')
结果:
Q1
you have won five point
Q2
5-4 外星人颜色#2:像练习 5-3那样设置外星人的颜色,并编写一个 if-else 结构。
如果外星人是绿色的,就打印一条消息,指出玩家因射杀该外星人获得了 5 个点。
如果外星人不是绿色的,就打印一条消息,指出玩家获得了 10个点。
编写这个程序的两个版本,在一个版本中执行 if 代码块,而在另一个版本中执行 else 代码块。
#Q1
print("Q1")
alien_color = 'green'
if alien_color == 'green':
print('you have won five point')
else:
print('you have won ten point')
#Q2
print("\nQ2")
alien_color = 'green'
if alien_color == 'green':
print('you have won five point')
else:
print('you have won ten point')
结果:
Q1
you have won five point
Q2
you have won five point
5-5 外星人颜色#3:将练习 5-4中的 if-else 结构改为 if-elif-else 结构。
如果外星人是绿色的,就打印一条消息,指出玩家获得了 5个点。
如果外星人是黄色的,就打印一条消息,指出玩家获得了 10个点。
如果外星人是红色的,就打印一条消息,指出玩家获得了 15个点。
编写这个程序的三个版本,它们分别在外星人为绿色、黄色和红色时打印一条消息。
#Q1
print('Q1')
alien_color = 'green'
if alien_color == 'green':
print('you have won five point')
elif alien_color == 'yellow':
print('you have won ten point')
else:
print('you have won fifteen point')
#Q2
print('\nQ2')
alien_color = 'yellow'
if alien_color == 'green':
print('you have won five point')
elif alien_color == 'yellow':
print('you have won ten point')
else:
print('you have won fifteen point')
#Q3
print('\nQ3')
alien_color = 'red'
if alien_color == 'green':
print('you have won five point')
elif alien_color == 'yellow':
print('you have won ten point')
else:
print('you have won fifteen point')
结果:
Q1
you have won five point
Q2
you have won ten point
Q3
you have won fifteen point
5-6 人生的不同阶段:设置变量 age 的值,再编写一个 if-elif-else 结构,根据 age的值判断处于人生的哪个阶段。
如果一个人的年龄小于 2岁,就打印一条消息,指出他是婴儿。
如果一个人的年龄为 2(含)~4岁,就打印一条消息,指出他正蹒跚学步。
如果一个人的年龄为 4(含)~13岁,就打印一条消息,指出他是儿童。
如果一个人的年龄为 13(含)~20岁,就打印一条消息,指出他是青少年。
如果一个人的年龄为 20(含)~65岁,就打印一条消息,指出他是成年人。
如果一个人的年龄超过 65(含)岁,就打印一条消息,指出他是老年人。
age = 5
if age < 2:
print("It is a baby")
elif age >= 2 and age < 4:
print("It learns walking")
elif age >= 4 and age < 13:
print('he is a child')
elif age >= 13 and age < 20:
print('he is a teenager')
elif age >= 20 and age < 65:
print('he is an adult')
else:
print('he is a the old')
结果:
he is a child
5-7 喜欢的水果:创建一个列表,其中包含你喜欢的水果,再编写一系列独立的 if语句,检查列表中是否包含特定的水果。
将该列表命名为 favorite_fruits ,并在其中包含三种水果。
编写 5条 if 语句,每条都检查某种水果是否包含在列表中,如果包含在列表中,就打印一条消息,如“You really like bananas!”。
favorite_fruits = ['banana','orange','apple']
if 'orange' in favorite_fruits:
print('you really like orange')
if 'apple' in favorite_fruits:
print('you really like apple')
if 'banana' in favorite_fruits:
print('you really like banana')
if 'mango' in favorite_fruits:
print('you really like mango')
if 'pipeapple' in favorite_fruits:
print('you really like pipeapple')
结果:
you really like orange
you really like apple
you really like banana
5.4 使用 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!
- 确定列表不是空的
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?
- 使用多个列表
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-8 以特殊方式跟管理员打招呼:创建一个至少包含 5个用户名的列表,且其中一个用户名为 ‘admin’ 。想象你要编写代码,在每位用户登录网站后都打印一条问候消息。遍历用户名列表,并向每位用户打印一条问候消息。
如果用户名为 ‘admin’ ,就打印一条特殊的问候消息,如“Hello admin, would you
like to see a status report?”。
否则,打印一条普通的问候消息,如“Hello Eric, thank you for logging in again”。
users = ['lily','admin','Eric','Susan','Lucy']
for user in users:
if user == 'admin':
print('Hello admin, would you like to see a status report?')
else:
print('hello %s,thank you for logging in again.'%user)
结果:
hello lily,thank you for logging in again.
Hello admin, would you like to see a status report?
hello Eric,thank you for logging in again.
hello Susan,thank you for logging in again.
hello Lucy,thank you for logging in again.
5-9 处理没有用户的情形:在为完成练习 5-8编写的程序中,添加一条 if 语句,检查用户名列表是否为空。
如果为空,就打印消息“We need to find some users!”。
删除列表中的所有用户名,确定将打印正确的消息
users = []
if users:
for user in users:
if user == 'admin':
print('Hello admin, would you like to see a status report?')
else:
print('hello %s,thank you for logging in again.' % user)
print("We need to find some users!")
结果:
We need to find some users!
5-10 检查用户名:按下面的说明编写一个程序,模拟网站确保每位用户的用户名都独一无二的方式。
创建一个至少包含 5个用户名的列表,并将其命名为 current_users 。
再创建一个包含 5个用户名的列表,将其命名为 new_users ,并确保其中有一两个用户名也包含在列表 current_users 中。
遍历列表 new_users ,对于其中的每个用户名,都检查它是否已被使用。如果是这样,就打印一条消息,指出需要输入别的用户名;否则,打印一条消息,指出这个用户名未被使用。
确保比较时不区分大消息;换句话说,如果用户名 ‘John’ 已被使用,应拒绝用户名 ‘JOHN’ 。
current_users = ['lily','Lucy','Xisan','lay','Susan']
new_users = ['Lily','Lucus','santi','youyou','Susan']
for user in new_users:
if user in current_users or user.lower() in current_users or user.upper() in current_users or user.title() in current_users:
print(user +' had been used,please enter another user name')
else:
print(user +' not been used')
结果:
Lily had been used,please enter another user name
Lucus not been used
santi not been used
youyou not been used
Susan had been used,please enter another user name
5-11 序数:序数表示位置,如 1st和 2nd。大多数序数都以 th结尾,只有 1、2和 3例外。
在一个列表中存储数字 1~9。
遍历这个列表。
在循环中使用一个 if-elif-else 结构,以打印每个数字对应的序数。输出内容应为 1st 、 2nd 、 3rd 、 4th 、 5th 、 6th 、 7th 、 8th 和 9th , 但每个序数都独占一行。
nums = list(range(1,10))
for num in nums:
if num == 1:
print('%dst'%num)
elif num == 2:
print('%dnd'%num)
elif num == 3:
print('%drd'%num)
else:
print('%dth'%num)
结果:
1st
2nd
3rd
4th
5th
6th
7th
8th
9th