阿里云服务器怎么使用,seo是干啥的,广州官网优化,留学网站 模板Python3使用独立的if语句与使用if-elif-else结构的不同之处
if-eliff-else结构功能强大#xff0c;但是仅适合用于只有一个条件满足的情况#xff1a;遇到通过了的测试后#xff0c;Python就跳过余下的测试。
然而#xff0c;有时候必须检查你关心的所有条件。在这种情况下…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