5.1 一个简单示例
# cars.py
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
5.2 条件测试
每条if语句的核心都是一个值为True或False的表达式,这种表达式称为条件测试。
5.2.1 检查是否相等
大多数条件测试将一个变量的当前值同特定值进行比较。
相等运算符在两边的值相等时返回True,否则返回False。
5.2.2 检查是否相等时忽略大小写
如果大小写无关紧要,只想检查变量的值,可将变量的值转换为小写,再进行比较。
car = 'Audi'
car.lower() == 'audi'
print(car)
5.2.3 检查是否不相等
要判断两个值是否不等,可结合使用惊叹号和等号(!=)。
# toppings.py
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
5.2.4 数值比较
# magic_number.py
answer = 17
if answer != 42:
print("That is not the correct answer. Please try again!")
条件语句中可包含各种数学比较,如等于(==)、不等于(!=)、小于(<)、小于等于(<=)、大于(>)、大于等于(>=)。
5.2.5 检查多个条件
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
2、使用or检查多个条件
只要至少一个条件满足,就能通过整个测试,仅当两个测试都没有通过时,使用or的表达式才为False。
>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 or age_1 >= 21
True
>>> age_0 = 18
>>> age_0 >= 21 and 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(f"{user.title()}, you can post a response if you wish")
5.2.8 布尔表达式
布尔表达式是条件测试的别名,布尔表达式的结果要么为True,要么为False。
5.3 if语句
5.3.1 简单的if语句
if conditional_test:
do something
# voting.py
age = 19
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
5.3.2 if-else语句
# voting.py
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!")
5.3.3 if-elif-else语句
# amusement_park.py
age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $25.")
else:
print("Your admission cost is $40.")
if age < 4:
price = 0
elif age < 18:
price = 25
else:
price = 40
print(f"Your admission cost is ${price}.")
5.3.4 使用多个elif代码块
# amusement_park.py
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
elif age < 65:
price = 40
else:
price = 20
print(f"Your admission cost is ${price}.")
5.3.5 省略else代码块
Python并不要求if-elif结构后面必须有else代码块。else是一条包罗万象的语句,只要不满足任何if或elif中的条件测试,其中的代码就会执行。这可能引入无效甚至恶意的数据。如果知道最终要测试的条件,应考虑使用一个elif代码块来代替else代码块。这样就可以肯定,仅当满足相应的条件时,代码才会执行。
# amusement_park.py
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
elif age < 65:
price = 40
elif age >= 65:
price = 20
print(f"Your admission cost is ${price}.")
5.3.6 测试多个条件
如果只想执行一个代码块,就是用if-elif-else结构;如果要执行多个代码块,就使用一系列独立的if语句。
# toppings.py
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")
5.4 使用if语句处理列表
5.4.1 检查特殊元素
# toppings.py
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
print(f"Adding {requested_topping}")
print("\nFinished making your pizza")
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("\nFinished making your pizza")
5.4.2 确保列表不是空的
requested_toppings = []
# 在if语句中将列表名用作条件表达式时,Python将在列表至少包含一个元素时返回True,并在列表为空时返回False。
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?")
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(f"Adding {requested_topping}")
else:
print(f"Sorry, we don't have {requested_topping}")
print("\nFinished making your pizza")
5.5 设置if语句的格式
在条件测试的格式设置方面,PEP8提供的唯一建议是,在诸如==、>=和<=等比较运算符两边各添加一个空格。
5.6 小结
在本章中,你学习了:如何编写结果要么为True要么为False的条件测试;如何编写简单的if语句、if-else语句和if-elif-else结构,并且在程序中使用这些结构来测试特定的条件,以确定这些条件是否满足;如何在利用高效的for循环的同时,以不同于其他元素的方式对特定的列表元素进行处理。你还再次学习了Python就代码格式提出的建议,从而确保即便编写的程序越来越复杂,其代码依然是易于阅读和理解。
在第6章,你将学习Python字典。字典类似于列表,但让你能够将不同的信息关联起来。你将学习如何创建和遍历字典,以及如何将字典同列表和if语句结合起来使用。学习字典让你能够模拟更多现实世界的情形。