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

Python条件判断问题:非指定输入仍执行if分支求解决

Python条件判断逻辑错误修复

你的代码逻辑存在问题,if stuffed == "yes" or "Yes" 这一行的写法不符合Python的逻辑判断规则。or运算符的优先级会让代码实际判断的是 (stuffed == "yes") or "Yes",而在Python中,非空字符串会被视为布尔值True,所以不管stuffed输入的是什么,这个条件都会成立,导致price始终被赋值为15。

以下是几种正确的写法:

  • 分别对两种情况做相等判断,用or连接:
if stuffed == "yes" or stuffed == "Yes":
    price = 15
else:
    price = 10
  • 将输入转为小写(或大写)后判断,简化代码:
if stuffed.lower() == "yes":
    price = 15
else:
    price = 10
  • 用in关键字判断输入是否在目标列表中:
if stuffed in ["yes", "Yes"]:
    price = 15
else:
    price = 10

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 02:35:55