4.1 条件测试
#遍历一个列表,并以首字母大写的方式打印其中的汽车名,但对于汽车名'bmw',以全大写的方式打印
cars=['audi','bmw','subaru','toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
检查是否相等时不考虑大小写,例如,两个大小写不同的值会被视为不相等。
4.1.1 检查是否不相等
requested_topping='mushrooms'
if requested_topping !='anchovies':
print("Hold the anchovies!")
有时检查两个值是否不等的效率更高
4.2 检查多个条件
4.2.1 使用and检查多个条件
检查两个条件都为true,可以使用关键字and将两个条件合而为一;如果每个测试都通过了,整个表达式就为true,如果至少有一个测试没通过,整个表达式就为flase.
例如,检查是否两个人都不小于21岁
age_0=22
age_1=18
age_0 >=21 and age_1>=21
4.2.2 使用or检查多个条件
age_0=22
age_1=18
age_0 >=21 or age_1>=21
4.2.3 检查特定值是否包含在列表中
要判断特定的值是否已包含在列表中,可使用关键字in
requested_topping=['mushrooms','onions','pineapple']
'mushrooms' in requested_toppings
4.2.4 条件测试实例
car='subaru'
print("is car == 'subaru'? i predict true. ")
print(car == 'subaru')
4.3.1 if-elif-else
经常需要检查超过两个的情形,可以使用if-elif-else 结构,它依次检查每个条件测试,直到遇到通过了的条件测试.如果前一个测试通过了,就不进行下一个测试
age=12
if age<4:
price=0
elif age<18:
price=5
else:
price=10
外星人的颜色#1
if结构
alien_color='green'
if alien_color == 'green':
print("玩家获得了5个点")
alien_color='yellow'
if alien_color == 'green':
print("玩家获得了5个点")
if-else结构,一个执行if结构,另一个执行else结构
alien_color='green'
if alien_color == 'green':
print("玩家因射杀该外星人获得了5个点")
else:
print("玩家获得了10个点")
alien_color='yellow'
if alien_color == 'green':
print("玩家因射杀该外星人获得了5个点")
else:
print("玩家获得了10个点")
判断列表中是否包含特定的水果
favorite_fruits=['apple','banana','orange']
if apple in favorite_fruits:
print("you really like bananas")
if banana in favorite_fruites:
prints("you really like bananas")
首先判断列表是否为空
requested_toppings=[]
if requested_toppings:
print(" ")
else:
print(" ")