You need to enable JavaScript to run this app. Python数值百分比增减程序:输入decrease仍输出增长的问题问询
优惠活动
大模型
产品
解决方案
定价
更多

Python数值百分比增减程序:输入decrease仍输出增长的问题问询

问题根因

你的程序输入decrease仍走增长逻辑,是两处逻辑错误叠加导致的:

  • 核心触发bug:错误使用了布尔表达式的判断逻辑。原代码中写的if option == "increase" or "Increase": 并非判断输入值是否等于"increase"或"Increase"。按照Python运算符优先级规则,==的计算优先级高于or,该表达式等价于(option == "increase") or ("Increase")。由于非空字符串在Python布尔判断中恒为True,整个if分支的判断结果永远为真,无论你输入什么选项,代码都会直接执行增长计算的逻辑,后续的decrease分支永远不会被触发。
  • 附带的逻辑冗余:你为了匹配大小写同时写的"increase"/"Increase"、"decrease"/"Decrease"双判断,因为上述永远为真的if判断,完全没有执行机会。
修正方案

优化判断逻辑,从根源上避免无意义的硬字符串匹配:

  • 对用户输入的选项做预处理:去掉首尾冗余空格、统一转为小写,无需重复写两次大小写不同的字符串判断
  • 补全所有比较表达式,避免非空字符串带来的恒真判断

修正后的可运行代码:

print("Number increase or decrease by percent")
print("")
# 预处理用户输入的选项,兼容大小写、首尾空格的输入
option = input("Increase or decrease: ").strip().lower()
num = float(input("Number: "))
percent = float(input("Percent: "))
if option == "increase":
    value = num + (num / 100 * percent)
elif option == "decrease":
    value = num - (num / 100 * percent)
else:
    value = "输入无效,请输入increase或decrease选项"
print(value)

如果坚持保留原来的大小写硬匹配逻辑,至少要把每个or后的比较表达式补全,例如正确的if判断写法是if option == "increase" or option == "Increase":,否则就会触发前述的恒真判断bug。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.24 05:15:10