Python:带列表的 IF 语句

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

将列表与 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,else,elif

前言在编程时,我们写的代码要遵循语言结构和流程控制,流程控制包括:顺序控制、条件控制、以及循环控制。顺序控制就是按照正常的代码执行顺序,从上到下,从代码开头执行到代码结尾,依次执行每条语句。本次内容,...

「Python条件结构」if…elif…else成绩等级信息

功能要求由计算机对学生的成绩进行分级(补考、及格、中、良、优),其划分标准为:小于60为补考;60~70分为及格;70~80分为中;80~90分为良;90~100分为优。最终输出等级信息。从键盘上输入...