Python:带列表的 IF 语句

liftword6个月前 (12-13)技术文章60

将列表与 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 __name__ == &#39;__main__&#39; 的解释

1. 基本概念在Python中,`if __name__ == "__main__"`是一种常见的代码结构。`__name__`是一个内置变量,它的值取决于模块是如何被使用的。当一个P...

Python之if语句使用

在Python编程语言中,for语句是一个非常常用的控制流语句。它用于遍历一个序列(如列表、元组、字典等),并对每个元素执行一段代码。下面我们将详细介绍Python中for语句的使用方法。1、用if语...

Python中的if语句

#挑战30天在头条写日记#在Python编程语言中,if语句是一种基本的条件控制结构。它用于根据特定条件执行不同的代码块。本文将介绍Python中的if语句的基础知识、使用方法以及实际案例分析。一、...

40道python二级考试真题火爆互联网,完整版答案解析为你保驾护航

Python二级考试试题(一)1.以下关于程序设计语言的描述,错误的选项是:A Python语言是一种脚本编程语言B 汇编语言是直接操作计算机硬件的编程语言C 程序设计语言经历了机器语言、汇编语言、脚...