一、 条件测试
1、判断相等: ==
2、使用 and 判断多个条件: 条件均为 true 的时候,才是 true
类似于 && 与
3、使用 or 判断多个条件: 条件有一个为 true 的时候,就是 true
类似于 || 或
4、判断特定值是不是在列表中:用关键词 in / not in
requested_topping = ['mushrooms','onions','pineapple']
'mushrooms' in requested_topping
结果:
True
'car' not in requested_topping
结果:
True
二、if结构
1、简单 if 语句
age = 19
if age > 18:
print("You are old enough to vote!")
注意 if 语句后面要加冒号
2、if-else 语句
age = 19
if age > 18:
print("You are old enough to vote!")
else:
print("Sorry,you are too young to vote!")
注意,if else 后面都要加 冒号
3、if-elif-else 语句
age = 12
if age < 4:
print("Your admission cost is $0")
elif age < 18:
print("Your admisiion cost is $5")
else:
print("Your admission cost is $10")
三、增强程序的鲁棒性
加入我们在使用 if 语句判断某特殊元素是否在列表中时,列表必须是有元素的,若是空列表,即没有元素,那么会让程序崩溃或者出现莫名bug,所以在程序实现过程中,要考虑到以下:
1> 程序中要使用列表,那么在使用时一定要加上列表是否为空的判断
2> 调用列表的元素时,如果调用的不存在于列表,也就是 要求异常的情况下的防范方法
下面模拟客户点匹萨配料时的情况
# 这个是披萨店提供的配料
available_topping = ['mushrooms','olives','green peppers','pepperoni',
'extra cheese','pineapple']
# 这个是客户想要的配料
requested_toppings = ['mushrooms','french fires','extra cheese']
if available_topping: # 如果 available_topping 这个列表不空,那就正常进行
if requested_toppings:
for requested_topping in requested_toppings:
if requested_topping in available_topping:
print('Add ' + requested_topping + '.')
else:
print('Sorry we do not have ' + requested_topping + '.')
else:
print("Your requestd topping is empty!")
else:
print("Are you sure you want a plain pizza?")
print("\nFinished making your pizza!")
结果:
Add mushrooms.
Sorry wo donot have french fires.
Add extra cheese.
Finished making your pizza!
注意 在程序上我们用了 if 来判断这两个列表是否为空