Python 05 | if语句 | 5.2 条件测试
条件测试
编程时需要根据条件决定采取怎样的措施。请看下面的示例:
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bwm':
print(car.upper())
else:
print(car.title())
输出效果:
>>>
Audi
Bmw
Subaru
Toyota
每条if语句的核心是一个值为Ture或False的表达式,这种表达式称为条件测试。如果条件测试值为True,就执行if语句后面的代码,否则Python就忽视。
检查是否相等
检查是否相等时会考虑大小写。如果大小写不重要,可将变量的值转换为小写,再检查。
car = 'Audi'
print(car.lower() == 'audi')
检查不相等
要判断两个值是否不等,可以使用!=
,其中!
表示不
。
requested_toppings = 'mushroom'
if requested_toppings != 'anchovies':
print("Hold the anchovies!")
比较数字
检查数字是否不相等
answer = 17
if answer != 42:
print("That is not the correct answer. Please try again!")
输出:
>>> That is not the correct answer. Please try again!
检查多个条件
有时需要在两个条件为True时才执行操作,有时仅需一个为True即可,此时需要用到关键字and
和or
.
使用and
检查多个条件
answer = 17
answer_1 = 18
answer_2 =12
if answer_1 >= answer and answer_2 <= answer:
print("OK")
使用or
检查多个条件
answer = 17
answer_1 = 18
answer_2 =12
if answer_1 > answer or answer_2 > answer:
print("Fine")
检查特定值是否包含在列表中
有时执行操作前,需要检查列表中是否包含特定的值。例如,结束用户的注册过程前,可能需要检查提供的用户名是否已包含在用户名列表中。在地图程序中,可能需要检查用户的位置是否包含在已知位置列表中。要判断特定的值是否包含在列表中,使用关键字in
。
requested_toppings = ['mushroom', 'onions', 'pineapple']
if 'mushroom' in requested_toppings:
print("We got mushrooms!")
if 'pepperoni' in requested_toppings:
print('We got pepperoni!')
else:
print("We gotta buy some pepperoni!")
检查特定值是否不包含在列表中
要检查特定的值是否不在列表中,使用关键字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.")