Python:带列表的 IF 语句

liftword5个月前 (12-13)技术文章45

将列表与 if 语句组合在一起可以对数据处理方式进行强大的控制。

可以以不同的方式处理特定值,管理不断变化的条件,并确保代码在各种场景中按预期运行。

检查特殊项目:

可以在循环中使用 if 语句来处理列表中的特殊值。

以比萨店为例,其中列出了配料,程序会在将其添加到比萨饼中时宣布每个配料。

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

for requested_topping in requested_toppings:
    print(f"Adding {requested_topping}.")
    
print("\nFinished making your pizza!")

>>

Adding mushrooms.
Adding green peppers.
Adding extra cheese.
Finished making your pizza!

如果green peppers不可用,则可以使用 if 语句提供替代操作:

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(f"Adding {requested_topping}.")
        
print("\nFinished making your pizza!")

>>

Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.
Finished making your pizza!

检查 List 是否为空:

在处理列表之前,检查它是否包含任何项目非常有用。

如果列表有时可能为空,这一点尤其重要。

例如,如果没有要求配料,可以询问客户是否想要普通披萨:

requested_toppings = []

if requested_toppings:
    for requested_topping in requested_toppings:
        print(f"Adding {requested_topping}.")
    print("\nFinished making your pizza!")
else:
    print("Are you sure you want a plain pizza?")

>>

Are you sure you want a plain pizza?

如果列表包含 toppings,则输出将显示正在添加的 toppings。

使用多个列表:

还可以使用多个列表来处理客户请求和可用项目。

例如,在将请求的配料添加到披萨之前,检查它是否可用:

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(f"Adding {requested_topping}.")
    else:
        print(f"Sorry, we don't have {requested_topping}.")
        
print("\nFinished making your pizza!")

>>

Adding mushrooms.
Sorry, we don't have french fries.
Adding extra cheese.
Finished making your pizza!

设置if语句的样式:

遵循 PEP 8 准则,确保比较运算符周围有适当的间距以提高可读性:

if age < 4:

优于:

if age<4:

这不会影响 Python 解释代码的方式,但会提高其可读性。

相关文章

教你Python字典的妙用,消除繁琐的if判断

根据不同的条件进行不同的计算或操作,是很常见的需求。Python 有 if 语句可以实现。但是一旦分支很多,多个 if 就是使你眼花缭乱。我们有许多技巧(套路)来简化这一过程。 我会一连几篇文章,从简...

Python- 第 15 天 - IF 语句 - 核心 P原理

Python 中的条件语句概述:编程通常涉及检查条件并根据这些条件决定采取什么行动。Python if 语句:允许检查程序的当前状态并适当地响应该状态。目标: 学习编写允许检查相关条件的条件测试。将编...

Python if语句嵌套(入门必读)

在最简单的 if 语句中嵌套 if else 语句,形式如下:if 表达式 1: if 表示式 2: 代码块 1 else: 代码块 2再比如,在 if else 语句中嵌套 if else 语句,形...

Python小技巧学起来!如何简化大量的 if…elif…else 代码?

今天在 Github 阅读EdgeDB[1]的代码,发现它在处理大量if...elif...else判断的时候,使用了一个非常巧妙的装饰器。我们来看看这个方法具体是什么样的。正好双十二快到了,假设我们...

Python短文,关于 if/else 条件语句(五)

转载说明:原创不易,未经授权,谢绝任何形式的转载在有些情况下,我们可能只想在满足特定条件时才执行某段代码。这可以通过if语句来实现。if语句 在Python中,if语句可以让您在满足特定条件时执行某些...