2017.5.4 if_3

1. 检查特殊元素

在for语句中嵌套if语句:

request_toppings = ['mushrooms','green peppers','extra cheese']

for request_topping in request_toppings:  #遍历其中每一个元素

    if(request_topping == 'green peppers'): #判断遍历过的元素是否有等于green peppers的

        print("Sorry, we are run out of green peppers")

    else:

        print("Adding " + request_topping + '.')

print("\nFinished your pizza!")

2. 检查空元素

request_toppings = []

if request_toppings:  #判断是否是空元素,如果不是空,执行跟上面相同的步骤

    for request_topping in request_toppings:

        print("Adding " + request_topping)

    print("\nFinished your pizza!")

else:  #如果是空元素有如下输出

    print("Are you sure you want a plain pizza?")

3. 多个列表

available_toppings = ['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese']

request_toppings = ['mushrooms','french fries','extra cheese']

for request_topping in request_toppings: #遍历第二个列表中所有元素

    if request_topping in available_toppings: #判断是否第二个列表中的所有元素都在第一个列表中

        print("Adding " + request_topping + '.')

    else:

        print("Sorry we donot have " + request_topping + '.')

print("\nFinished making your pizza!")

你可能感兴趣的:(2017.5.4 if_3)