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

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 is instead of == for string comparison: is checks 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 or condition structure: Lines like if 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 first if block!

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 is for == 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 or checks 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:24:26