if语句
1.检查多个条件
1.1 使用and检查多个条件
and 两者同时满足
>>> age_0=22
>>> age_1=18
>>> age_0>=21 and age_1>=21
False
>>>
1.2 使用or检查多个条件
or 其中一个条件满足
age_0=22
age_1=18
print(age_0>=21 or age_1>=21)
True
2.检查特定值是否不包含在列表中
可以使用关键字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 #就是因为不在其中,所以才能看到这句话
3.检查特定值是否包含在列表中
requested_toppings = ['mushrooms','onions','pineapple']
print('mushrooms' in requested_toppings)
True
4.使用if语句处理列表
4.1 确定列表是否为空
在if语句中将列表名用在条件表达式中时,python将在列表至少包含一个元素时返回True,并在列表为空时返回False.
request_toppings=[]
if request_toppings:
for request_topping in request_toppings:
print("Adding "+request_topping)
else:
print("Are you sure you want a plain pizza?")
Are you sure you want a plain pizza? #列表为空,返回False,执行else语句里面的代码