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的表达式,这种表达式被称为条件测试。Python根据条件测试的值为True还是False来决定是否执行if语句中的代码。如果条件测试的值为True,Python就执行紧跟在if语句后面的代码;如果为False,Python就忽略这些代码。
检查是否相等
>>>car = 'bmw'
>>>car == 'bmw'
True
检查是否不相等
>>>car = 'bmw'
>>>car != 'toyota'
True
检查多个条件
-
使用
and检查好多个条件,相当于 Javascript 中&&>>>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 -
使用
or检查多个条件,相当于 Javascript 中||>>>age_0 = 22 >>>age_1 = 18 >>>age_0 >= 21 or age_1 >=21 True >>>age_0 = 18 >>>age_0 >=21 or age_1 >=21 False
检查特定值是否包含在列表中
要判断特定的值是否已包含在列表中,可使用关键字 in。
比如,你可能为披萨店编写的一些代码,这些代码首先创建一个列表,其中包含用户点的比萨配料,然后检查特定的配料是否包含在该列表中。
>>> requested_toppings = ['mushrooms', 'onions', 'pineapple']
>>> 'mushrooms' in requested_toppings
True
>>> 'pepperoni' in requested_toppiongs
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.")
Marie, you can post a response if you wish
布尔表达式
随着你对编程的了解越来越深入,将遇到术语布尔表达式,它不过是条件测试的别名。与条件表达式一样,布尔表达式的结果要么为True,要么为False。布尔值通常用于记录条件,如游戏是否正在运行,或用户是否可以编辑网站的特定内容:
game_active = True
can_edit = False
if 语句
简单的 if 语句
最简单的if语句只有一个测试个操作:
if conditional_test:
do something
if - else 语句
age = 17
if age >= 18:
print('You are old enough to vote')
else:
print('You are too young to vote')
if - elif - else 结构
在现实世界中,很多情况下需要考虑的情形都超过两个。例如,来看一个根据年龄段收费的游乐场:
- 4岁以下免费;
- 4~18岁收费5美元;
- 18岁(含)以上收费10美元。
age = 12
if age < 4:
pricae = 0
elif age < 18:
price = 5
else:
price = 10
使用多个 elif 代码块
可根据需要使用任意数量的elif代码块,例如,假设前述游乐场要给老年人打折,可再添加一个条件测试,判断顾客是否符合打折条件。下面假设对于65岁(含)以上的老人,可以半价(即5美元)购买门票:
age = 12
if age < 4:
pricae = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
else:
price = 5
省略 else 代码块
Python并不要求if-elif结构后面必须有else代码块。
确定列表不是空的
在if语句中将列表名用在条件表达式中时,Python将在列表至少包含一个元素时返回True,并在列表为空时返回False
users = []
if users:
print('not empty')
else:
print('empty')
empty
tips: 明天讲 Python 中的 字典