You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何结合if语句与循环调用函数?编程新手求助

Hey there! Let's break down what's going on with your code and fix it step by step. I totally get being a new programmer—we've all been there, so no worries at all!

Issues with your current code

  • You're looping over the wrong list: Your for item in toppings loop is checking the predefined toppings instead of the incoming order list. We need to validate each item in the user's order, not the allowed list itself.
  • The first if condition is broken: 'salmon' or 'tuna' or 'whitefish' in toppings doesn't work as intended. In Python, non-empty strings evaluate to True, so this condition will always be True—it skips straight to printing "all set" and breaks the loop, never checking any items in the order.
  • Incorrect use of append(): toppings.append(order) adds the entire order list to toppings instead of individual items, plus append() returns None, which is why you'd see "Add to this None" instead of the actual invalid item.

Fixed code

def sushi(order):
    # Predefined allowed sushi toppings
    toppings = ['salmon', 'tuna', 'whitefish']
    
    # Check each item in the incoming order
    for item in order:
        if item not in toppings:
            print(f'Add to this {item}')
            # Optional: Add the new topping to the allowed list if needed
            toppings.append(item)
    
    # Print "all set" once all items are checked
    print('all set')

# Test the function with your sample inputs
sushi(['salmon', 'tuna'])
sushi(['salmon', 'tuna', 'tempura'])

What this does

When you run this code, you'll get exactly the output you expected:

all set
Add to this tempura
all set

Here's the breakdown:

  1. For sushi(['salmon', 'tuna']), every item is in the predefined toppings list, so we skip the if block and just print "all set".
  2. For sushi(['salmon', 'tuna', 'tempura']), we hit the if block when we reach "tempura"—we print the required message, add it to the toppings list (remove that line if you don't want to update the allowed list), then after checking all items, print "all set".

内容的提问来源于stack exchange,提问作者kimi315

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:13:43