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

Python条件判断语句逻辑错误排查:CS50p作业疑问

CS50p作业问题原因解析

你最初的代码之所以不管输入什么都输出"Yes",核心是犯了Python逻辑判断里的常见低级错误——错误的多条件或运算写法。

错误代码的典型形式

你写的第一段代码大概率是这样的:

answer = input("What's the answer to the ultimate question of life, the universe, and everything? ").strip().lower()
if answer == "42" or "forty-two" or "forty two":
    print("Yes")
else:
    print("No")

这里的问题在于:Python里or运算符是逐个判断每个子表达式的布尔值。"forty-two"和"forty two"都是非空字符串,在布尔语境下会被直接判定为True。所以不管answer是什么值,整个if条件都会因为后面的or "forty-two"直接成立,自然永远输出"Yes"。

为什么拆分elif的版本能正常运行

你后来改成的拆分elif版本应该是类似这样:

answer = input("What's the answer to the ultimate question of life, the universe, and everything? ").strip().lower()
if answer == "42":
    print("Yes")
elif answer == "forty-two":
    print("Yes")
elif answer == "forty two":
    print("Yes")
else:
    print("No")

这种写法是逐个判断answer是否等于目标值,只有当某一个==判断成立时才会输出"Yes",所有条件都不满足时才走else分支输出"No",逻辑完全正确。

更简洁的正确写法

除了拆分elif,你也可以用正确的多条件或运算形式,或者用集合的in运算符让代码更简洁:

# 正确的多条件或运算
answer = input("What's the answer to the ultimate question of life, the universe, and everything? ").strip().lower()
if answer == "42" or answer == "forty-two" or answer == "forty two":
    print("Yes")
else:
    print("No")

# 集合in运算符写法(更简洁)
answer = input("What's the answer to the ultimate question of life, the universe, and everything? ").strip().lower()
if answer in {"42", "forty-two", "forty two"}:
    print("Yes")
else:
    print("No")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 09:16:34