首页 > 解决方案 > 如何使用循环列表的 if 语句调用函数?Python

问题描述

在这里编程是全新的,并且在家庭作业问题上遇到了很多麻烦。请原谅我缺乏理解和知识。任何帮助将不胜感激!谢谢!!当我正在调用的项目之一不在列表中时,我正在尝试输出一个 if 语句,并且该函数应该打印出该项目。

def sushi(order):
    toppings = ['salmon', 'tuna', 'whitefish']
    for item in toppings:
        if 'salmon' or 'tuna' or 'whitefish' in toppings:
            print('all set')
            break
        if not item in toppings:
            print('Add to this', toppings.append(order))
            print('all set')

sushi(['salmon', 'tuna'])
sushi(['salmon', 'tuna', 'tempura'])

我希望它输出:

all set
Add to this tempura
all set

标签: pythonloopsif-statement

解决方案


我相信您正在寻找的是:

def sushi(order):
    toppings = ['salmon', 'tuna', 'whitefish']
    for item in order:
        if item not in toppings:
            print('Add to this', item)
    print("All set!")

>>> sushi(['salmon', 'tuna'])
All set!
>>> sushi(['salmon', 'tuna', 'tempura'])
Add to this tempura
All set!

可以通过将其更改为来缩短循环:

for item in [x for x in order if x not in toppings]:
    print('Add to this', item)

你的问题是:

1)for item in toppings:

我猜你想要这里order而不是toppings

2)if 'salmon' or 'tuna' or 'whitefish' in toppings:

在这里,您可能希望它是:if 'salmon' in toppings or 'tuna' in toppings or 'whitefish' in toppings:. 你写的是“如果字符串'salmon'存在或字符串'tuna'存在或字符串'whitefish'在浇头中”。

3)print('Add to this', toppings.append(order))

该方法append不返回任何内容。也许你想要的是添加一行说toppings.append(item)然后简单地打印item


推荐阅读