Python3使用独立的if语句与使用if-elif-else结构的不同之处


Python3使用独立的if语句与使用if-elif-else结构的不同之处

if-eliff-else结构功能强大,但是仅适合用于只有一个条件满足的情况:遇到通过了的测试后,Python就跳过余下的测试。

然而,有时候必须检查你关心的所有条件。在这种情况下,应使用一系列不包含else和else代码块简单if语句

下面来看一个早餐店的实例。如果顾客点了一个鸡蛋卷,并点了两种种配料,要确保这个鸡蛋卷包含这些配料

toopings.py

requested_toppings = ['pepperoni','mushrooms']

if 'pepperoni' in requested_toppings:
    print("Adding pepperoni")
if 'lettuce' in requested_toppings:
    print("Adding lettuce")
if 'potato' in requested_toppings:
    print("Adding potato")
if 'mushrooms' in requested_toppings:
    print("Adding mushrooms")

print("\nFinished making your breakfast!")

输出:


Adding pepperoni
Adding mushrooms

Finished making your breakfast!


首先创建了一个列表,其中包含顾客点的配料。然后第一个 if 语句检查是否顾客点了配料辣香肠(‘pepperoni’),因为接下来也是简单的 if 语句,而不是 elif和else 语句,所以不管前一个测试是否通过, 都将进行这个测试。 然后第二,三个的 if 语句判断没点 生菜(‘lettuce’)和 土豆(‘potato’),判断第四个 if 点了 蘑菇(‘mushrooms’)。每当这个程序运行时,都会进行这三个独立的测试。

requested_toppings = ['pepperoni','mushrooms']

if 'pepperoni' in requested_toppings:
    print("Adding pepperoni")
elif 'lettuce' in requested_toppings:
    print("Adding lettuce")
elif 'potato' in requested_toppings:
    print("Adding potato")
elif 'mushrooms' in requested_toppings:
    print("Adding mushrooms")

print("\nFinished making your breakfast!")

输出:


Adding pepperoni

Finished making your breakfast!


第一个测试检查列表是否包含‘pepperoni’,通过了,因此将此辣香肠添加。但是将跳过其余if-elif-else结构中余下的测试。

总之, 如果只想执行一个代码块, 就使用if-elif-else结构;如果要运行多个代码块,就使用一些独立的 if 语句。

转载自:https://blog.csdn.net/viviliao_/article/details/79561651

You may also like...

退出移动版