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 toppingsloop is checking the predefined toppings instead of the incomingorderlist. We need to validate each item in the user's order, not the allowed list itself. - The first
ifcondition is broken:'salmon' or 'tuna' or 'whitefish' in toppingsdoesn't work as intended. In Python, non-empty strings evaluate toTrue, so this condition will always beTrue—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, plusappend()returnsNone, 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:
- For
sushi(['salmon', 'tuna']), every item is in the predefined toppings list, so we skip theifblock and just print "all set". - For
sushi(['salmon', 'tuna', 'tempura']), we hit theifblock 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
相关产品推荐
相关产品推荐

