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

Python石头剪刀布游戏新增重玩功能时elif语句无法触发如何解决

问题修复方案

你代码里有两个核心错误导致底部elif无法执行:

  • 第一个错误:获取重玩输入的代码里,字符串小写方法漏写了调用括号
    原代码:again = input("\nDo you want to play again? (yes/no): \n").lower
    这里的lower是函数对象本身,没有执行调用,你得到的again变量不是处理后的小写字符串,而是函数本身,自然无法和后续的"yes""no"字符串匹配。
  • 第二个错误:逻辑判断的or用法不符合Python语法规则
    原代码的if again == "yes" or "ye" or "y"写法,实际执行逻辑是if (again == "yes") or (bool("ye")) or (bool("y")),非空字符串的布尔值恒为True,所以这个if判断永远成立,后续的elif分支永远不会被触发。

修复后的代码片段(对应你标注的问题区域)

# 修复1:添加lower的调用括号
    again = input("\nDo you want to play again? (yes/no): \n").lower()

# Start of problem ---------------------------------------------------
    # 修复2:用in判断成员关系替代错误的or写法
    if again in ["yes", "ye", "y"]:
        ai = random.choice(choices)
        player = input("Enter rock, paper, or scissors: ").lower()
        continue
    elif again in ["no", "n"]:
        break
# End of problem -----------------------------------------------------

额外优化建议(非必须,不影响功能)

你代码里胜负判断部分的in choices是多余逻辑:你已经提前校验过玩家输入一定在choices里,AI的选择也是直接从choices里随机取的,所以每个if条件里的in choices都可以删掉,简化代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:48:05