python编程-从入门到实践-if语句
- 一个简单的if语句
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
结果显示:
Audi
BMW
Subaru
Toyota
- 在程序中可以用来检查程序的测试-条件测试
car = 'bmw'
car == 'bmw'
true
大多数条件测试都将一个变量的当前值同特定值进行比较。
最简单的条件测试检查变量的值是否与特定值相等
检查是否相等时不考虑大小写
- 在Python中检查是否相等时区分大小写,例如,两个大小写不同的值会被视为不相等
- 如果大小写无关紧要,而只想检查变量的值,可将变量的值转换为小写,再进行比较
car = 'Audi'
car.lower() == 'audi'
True
这样转化为小写但是并没有影响存储在变量car 中的值,此刻依然为Audi
检查是否不相等(!=)
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
结果显示:
Hold the anchovies!
比较数字
age = 18
age == 18
True
条件语句中可包含各种数学比较,如小于、小于等于、大于、大于等于
age = 19
age < 21 True
age <= 21 True
age > 21 False
age >= 21
False
使用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
为了增加可读性,可以使用括号:
(age_0 >= 21) and (age_1 >= 21)
使用or检查多个条件
age_0 = 22
age_1 = 18
age_0 >= 21 or age_1 >= 21
True
检查特定值是否包含在列表中-关键字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.")
布尔表达式-结果要么为True ,要么为False
在if 语句中,缩进的作用与for 循环中相同。如果测试通过了,将执行if 语句后面所有缩进的代码行,否则将忽略它们。
if-elif-else 结构,也可以使用多个elif 代码块
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.")
Python并不要求if-elif 结构后面必须有else 代码块。可以省略else
测试多个条件-使用多个if
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语句处理列表
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?")