1. 简单判断是否相等
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
如果要忽略大小写可以使用str.lower()转成小写,或者str.upper()转成大写再判断
2. 检查多个条件
2.1 使用 and 检查多个条件
要检查两个条件都为True,可使用关键字and将两个条件测试连接起来。
age_0 = 22
age_1 = 18
if age_0 >= 21 and age_1 >= 21:
print('two age >= 21')
else:
print('not all age >=21')
2.2 使用or检查多个条件
要检查两个条件存在一个为True,条件即满足,可使用or。
age_0 = 22
age_1 = 18
if age_0 >= 21 or age_1 >= 21:
print('have one age >= 21')
else:
print('not one age >=21')
3. 检查特定值是否包含在列表中
即判断某个元素是否属于列表
requested_toppings = ['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms")
#检查特定值是否不包含在列表中
if 'x' not in requested_toppings:
print("x not in ")
4. if-elif-else 结构
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
else:
price = 40
print(f"Your admission cost is ¥{price}.")