Python:带列表的 IF 语句
将列表与 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 解释代码的方式,但会提高其可读性。