目录
使用 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 的表达式,如果条件测试的值为 True,Python 就执行紧跟在 if 语句后面的代码;如果为False,Python 就忽略这些代码。
1、检查是否相等
字符、数值均可使用:
相等运算符:==
不等运算符:!=
2、检查多个条件
检查两个条件是否都为 True,可使用关键字 and 将两个条件测试合而为一。如果每个条件测试都通过了,整个表达式就为 True;如果至少一个条件测试没有通过,整个表达式就为 False
(age_0 >= 21) and (age_1 >= 21)
关键字 or 也能够让你检查多个条件,但只要满足其中一个条件,就能通过整个条
件测试。仅当所有条件测试都没有通过时,使用 or 的表达式才为 False
(age_0 >= 21) or (age_1 >= 21)
3、检查特定的值是否“在 or 不在”列表中
# in 和 not in
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(f"{user.title()}, you can post a response if you wish.")
二、if 语句
1、if-else
age = 17
if age >= 18:
print("你成年了!")
else:
print("Sorry, 你还太小")
2、if-elif-else
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
else:
price = 40
print(f"花费芥末多 ${price}.")
注意:都需要在最后加上 :
可以结合上一篇对列表的操作,引入 if 语句,检查列表的特殊元素等等