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

数字游戏中含or运算符的条件语句无法正常运行问题咨询

问题分析与解决办法

核心错误:条件判断逻辑写法错误

你的if/elif条件里的or用法完全不对。比如start_game == "Yes" or "yes",Python会将其解析为(start_game == "Yes") or ("yes"),而非空字符串在布尔判断中永远为True,所以不管start_game是什么值,这个条件都会成立,导致第一个if分支总是执行——哪怕你输入的是"no",游戏也会启动。

正确的条件写法

有两种常用的修正方式,选一种即可:

  1. 每个分支都完整写比较表达式:
if start_game == "Yes" or start_game == "yes":
    print("Let's begin: ")
    print(random_number_one)
    input("Do you think the next number will be higher or lower? Type 'H' for higher or 'L' for lower:  ")
elif start_game == "No" or start_game == "no":
    print("Okay, maybe next time.")
else:
    print("Invalid response. You lose.")
  1. 用in判断输入是否在目标列表中(更简洁):
if start_game in ["Yes", "yes"]:
    print("Let's begin: ")
    print(random_number_one)
    input("Do you think the next number will be higher or lower? Type 'H' for higher or 'L' for lower:  ")
elif start_game in ["No", "no"]:
    print("Okay, maybe next time.")
else:
    print("Invalid response. You lose.")

还可以把输入统一转成小写(或大写)进一步简化判断:

start_game = start_game.lower()  # 先把输入转成小写
if start_game == "yes":
    # 游戏逻辑
elif start_game == "no":
    # 结束提示
else:
    # 无效输入提示

其他需要检查的问题

  • 确认你已经将用户输入赋值给了start_game变量,比如start_game = input("Do you want to play? (Yes/No): "),否则start_game会未定义报错。
  • 确认random_number_one变量已经被正确定义并赋值,否则执行到print(random_number_one)时会抛出未定义错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 10:21:12