5 第五章 if语句
一个简单示例
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
# Audi
# BMW
# Subaru
# Toyota
条件测试
条件测试: 每条if 语句的结果要么是True ,要么是False ;
Python根据条件测试的值为True 还是False 来决定是否执行if 语句中的代码
A == B:A等于B,则结果为True,否则为False
A != B: A不等于B,则结果为True,否则为False
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
# Hold the anchovies!
条件语句中可包含各种数学比较,如小于(<)、小于等于(<=)、大于(>)、大于等于(>=)
# 使用and 检查多个条件
age = 30
if age > 18 and age < 60:
print("good")
# good
# 使用 or 检查多个条件
age = 9
if age > 18 or age < 10:
print("good_2")
# good_2
要判断特定的值是否已包含在列表中,可使用关键字in;
要判断特定的值是否未包含在列表中,可使用关键字not in
布尔表达式的结果要么为True ,要么为False ;
布尔值通常用于记录条件,如游戏是否正在运行,或用户是否可以编辑网站的特定内容
if语句
if conditional_test:
do something
# 如果条件测试的结果为True ,Python就会执行紧跟在if语句后面的代码;
# 否则Python将忽略这些代码
age = 19
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
# You are old enough to vote!
# Have you registered to vote yet?
# 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:
price = 0
elif age < 18:
price = 5
else:
price = 10
print("Your admission cost is $" + str(price) + ".")
# 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) + ".")
# 省略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) + ".")
# 该处的elif 代码块在顾客的年龄超过65(含)时,就将价格设置为5美元;
# 这比使用else 代码块更清晰些
# 经过这样的修改后,每个代码块都仅在通过了相应的测试时才会执;
# 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!")
# Adding mushrooms.
# Adding extra cheese.
# Finished making your pizza!
使用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!
设置if语句的格式
在条件测试的格式设置方面,PEP 8提供的唯一建议是:
在诸如== 、>= 和<= 等比较运算符两边各添加一个空格,
例如,if age < 4: 要比 if age<4: 好;
这样的空格不仅不会影响Python对代码的解读,还会让代码阅读起来更容易
小结
条件测试;if、if-else、if-elif-else结构;
Python在代码格式方面的建议,这可确保即便你编写的程序越来越复杂,但其代码依然易于阅读和理解
人生便是艺术。