示例代码:
cars = ['audi','bmw','subaru','toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
1、条件测试:
-
检查是否相等、是否不相等
-
检查多个条件
-
使用and检查多个条件。
-
使用or检查多个条件。
-
检查特定值是否包含在列表中。(in , not in)
requested_toppings = ['mushrooms','onions','pineapple'] 'mushrooms' in requested_toppings true 'pepperoni' in requested_toppings false
-
布尔表达式
-
-
if-elif-else结构
2、使用if语句处理列表:
-
检查特殊元素。
#检查菜单中某项菜品是否用光 requested_toppings =['mushrooms','extra cheese','green pineapple'] for requested_topping in requested_toppings: if requested_topping == 'green pineapple': print("Sorry, we are out of green peppers right now.") else: print("Adding " + requested_topping + ".") print("\nFinished making your pizza!")
-
确定列表不是空的。
#检查顾客点的配料列表是否为空 requested_toppings = [] if requested_toppings: for requested_topping in requested_toppings: print("Adding " + requested_topping + ".") print("\nFinished making your pizza:") else: print("Are you sure you want a plain pizza?")
-
使用多个列表。
#检查客户的需求是否为披萨店供应的配料 available_toppings = ['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese'] requested_toppings = ['mushrooms','french fries','extra cheese'] for requested_topping in requested_toppings: if requested_topping in available_toppings: print("Adding " + requested_topping + ".") else: print("Sorry, we don't have " + requested_topping + ".") print("\nFinished making your pizza!")