第5章 if语句
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 条件测试
- 检查是否相等;
- 检查是否相等时不考虑大小写;
例如,两个大小写不同的值会被视为不相等。
car = 'Audi'
car == 'audi'
False
- 检查是否不相等;
- 比较数字;
- 检查多个条件:
(1)使用and检查多个条件;
(2)使用or检查多个条件; - 检查特定值是否包含在列表中:
requested_toppings = ['mushrooms', 'onions', 'pineapple']
'mushrooms' in requested_toppings
Ture
'pepperoni' in requested_toppings
False
- 检查特定值是否不包含在列表中:
banned_users.py
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.3 if语句
- 简单的if语句:
if conditional_test:
do something
-
if-else语句;
-
if-elif-else结构;
-
使用多个elif代码块;
-
省略else代码块:
经过这样的修改后,每个代码块都仅在通过了相应的测试时才会执行。
else是一条包罗万象的语句,只要不满足任何if或elif中的条件测试,其中的代码就会执行,这可能会引入无效甚至恶意的数据。如果知道最终要测试的条件,应考虑使用一个elif代码来代替else代码块。这样,你就可以肯定,仅当满足相应的条件时,你的代码才会执行。 -
测试多个条件:
有时候必须检查你关心的所有条件:
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!")
如果转而使用if-elif-else结构,代码将不能正确地运行,因为有一个测试通过后,就会跳过余下的测试。
总之,如果你只想执行一个代码块,就使用if-elif-else结构;如果要运行多个代码块,就使用一系列独立的if语句。
5.4 使用if语句处理列表
- 检查特殊元素;
- 确定列表不是空的;
- 使用多个列表:
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.5 设置if语句的格式
在条件测试的格式设置方面,PEP 8提供的唯一建议是,在诸如==、>=和<=等比较运算符两边各添加一个空格。这样的空格不会影响Python对代码的解读,而只是让代码阅读起来更容易。