cars = ['audi', 'bmw', 'subaru', 'toyota'] for car in cars: if car == 'bmw': print(car.upper()) else: print(car.title()) #output Audi BMW Subaru Toyota
1.条件测试
等于(==),大于(>),小于(<), 小于等于(<=),大于等于(>=)
and、or
检查特定值是否包含在列表中(in)、是否不包含在列表中(not in)
bool表达式(True、False)
2.使用if语句处理列表
以披萨店制作披萨为例,每添加一种配料都打印一条消息:
1 2 3 4 5 6 7 8 9 10 11
# usr if check list requested_toppings = ['mushrooms', 'green peppers', 'extra cheese'] for requested_topping in requested_toppings: print("Adding " + requested_topping + ".") print("\nFinished making your pizza!") #output Adding mushrooms. Adding green peppers. Adding extra cheese.
Finished making your pizza!
青椒用光了:
1 2 3 4 5 6 7 8 9 10 11 12 13
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese'] for requested_topping in requested_toppings: if requested_topping == 'green peppers': print("Sorry, we are out of green peppers right now.") else: print("Adding " + requested_topping + ".") print("\nFinished making your pizza!") #output Adding mushrooms. Sorry, we are out of green peppers right now. Adding extra cheese.
Finished making your pizza!
判断顾客点的配料列表是否为空:
1 2 3 4 5 6 7 8 9
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?") #output: Are you sure you want a plain pizza?
顾客的要求往往五花八门,下面定义两个列表。第一个包含披萨店供应的配料,第二个包含顾客点的配料。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
requested_toppings = ['mushrooms', 'french fires', 'extra cheese'] available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese'] for requested_topping in requested_toppings: if requested_topping in available_toppings: print("Adding " + requested_topping + ".") else: print("Sorry, we donot have " + requested_topping + ".") print("\nFinished making your pizza!") #output: Adding mushrooms. Sorry, we donot have french fires. Adding extra cheese.