Python条件判断代码问题求助:输入任意内容均输出‘Nice’
Fixing Your Python Condition Check Bug
Hey there! Great job writing your first Python code—let's get that little issue sorted out where every input prints "Nice" instead of the right message.
The Problem in Your Code
Your condition checks have two small but impactful mistakes:
- Using
isinstead of==for string comparison:ischecks if two objects are the exact same instance in memory, while==compares the actual value of the strings. For most cases, you want==when comparing text. - Incorrect
orcondition structure: Lines likeif x is "Apple" or "apple"don't work how you think. Python reads this as(x is "Apple") or ("apple")—and since non-empty strings are always "truthy", the"apple"part will always be True. That's why every input triggers the firstifblock!
Fixed Code
Here's the corrected version with cleaner, working logic:
print("Hi and welcome to our online shop.\n\nWhich fruit would you like to buy? Apple, Banana or Strawberry?") x = input() # Convert input to lowercase to handle any capitalization easily if x.lower() == "apple": print("Nice.") elif x.lower() == "banana": print("Great.") elif x.lower() == "strawberry": print("Cool.") else: print("Please enter an available product")
What Changed?
- Swapped
isfor==to correctly compare string values. - Used
x.lower()to convert the input to all lowercase—this way, inputs like "APPLE", "Apple", or "apple" will all match, making your code more user-friendly. - Removed the redundant
orchecks by using.lower()—no need to list every capitalization variant!
If you want to stick to checking exact matches without .lower(), you could write conditions like x == "Apple" or x == "apple", but the .lower() approach is cleaner.
Keep up the good work—you're off to a great start!
内容的提问来源于stack exchange,提问作者9cc9x
相关产品推荐
相关产品推荐

