第五章主要介绍了简单的if语句的使用方法,下面将对if语句进行简单的介绍
5.1 一个简单示例
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
5.2 条件测试
if语句会对需要判断的内容进行判断,
如果值为Ture将运行if语句的后续代码,如果为False,将忽略后续代码。
5.2.1 检查是否相等
car = 'bmw'
car == 'bmw'
在python中运行这两行代码,会返回True。
5.2.2 检查是否相等时不考虑大小写
在python中检查是否相等时区分大小写,
例如,两个大小写不同的值会被视为不相等。
我们可以在比较前先将所有待比较的值转化为小写,然后再进行比较。
5.2.3 检查是否不相等
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
5.2.4 数值比较
age = 17
if age != 58:
print("That is not the correct answer. Please try again!")
5.2.5 检查多个条件
1. 使用and检查多个条件
age_0 = 22
age_1 = 22
if age_0 >= 21 and age_1 >= 21:
print(100)
为了让我们的代码更具有可读性,我们可以将if之后的两个判断条件分别加上两个括号。
2. 使用or检查多个条件
age_0 = 100
age_1 = 1
age_0 = 0
if age_0 >= 21 or age_1 >= 21:
print(200)
在这里,or就是或的意思,and就是与的意思,类似于And、Or门电路。
5.2.6 检查特定值是否包含在列表中
requested_topping = ['mushrooms', 'onions', 'pineapple']
if 'mushrooms' in requested_topping:
print(1)
if 'pepperoni' in requested_topping:
print(2)
请注意:若要去处列表中的元素,请加上单引号:''
5.2.7 检查特定值是否不包含在列表中
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.")
5.2.8 布尔表达式
这个例子定义两个变量并赋予布尔类型的值,布尔类型的值就两个:True和False。
5.3 if语句
5.3.1 简单的if语句
5.3.1 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("Plse register to vote as soon as you turn 18!")
5.3.4 if- elif-else结构
age = 12
if age < 4:
price = 0
elif age < 25:
price = 25
else:
price = 40
print(f"The cost is ${price}.")
5.3.4 使用多个elif代码块
age = 50
if age < 4:
price = 0
elif age < 25:
price = 25
elif age < 65:
price = 40
else:
price = 20
print(f"The cost is ${price}.")
这里可以理解为:
若需要判断众多条件中的一个条件是否成立,
则if和else只能有一个,如果还要有其他判断,必须要使用elif语句
5.3.5 省略else代码块
age = 70
if age < 4:
price = 0
elif age < 25:
price = 25
elif age < 65:
price = 40
elif age >= 65:
price = 20
print(f"The cost is ${price}.")
此处可以理解为使用elif来代替了else,
但是要记住,else后直接跟冒号,而没有判断条件,所以在使用elif进行替换之后,要加入判断条件。
5.3.6 测试多个条件
请注意:若同时判断一些条件,则需要使用多条if语句。
但是若要判断众多条件中的一个条件是否成立,则要使用if-elif-else结构
5.4 使用if语句处理列表
5.4.1 检查特殊元素
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(f"Adding {requested_topping}")
print("Finished making your pizza!\n")
5.4.2 确定列表不是空的
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?\n")
5.4.3 使用多个列表
games = ['Sekiro', 'CSGO', 'CF', 'NiShuiHan', 'JW3']
mygames = ['Sekiro', 'YiMengJiangHu', 'QQCars']
for game in games:
if game not in mygames:
print(f"Please buy {game}!")
else:
print(f"The {game} is in your inventory!!!")