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

Python猜拳程序输入校验问题:如何在输入无效时重启循环?

石头剪刀布程序输入校验修复方案

你的核心问题是输入校验逻辑的顺序错误,导致无效输入时仍会执行后续胜负判断代码,或是干扰quit的正常退出流程。调整校验逻辑的位置即可解决:

  1. 先判断输入是否在合法列表内,若无效直接提示并重启循环,不执行后续游戏逻辑
  2. 再单独处理quit的退出分支
  3. 最后执行正常的游戏胜负判断逻辑

另外还修复了一个小bug:原代码中电脑随机选择时只取了前两个选项(valid_values[0:2]),漏掉了scissors,现在改为取前三个合法游戏选项。

修改后的完整代码:

import random
valid_values = ["rock", "paper", "scissors", "quit"]

victories = [
    ["paper", "rock"],
    ["rock", "scissors"],
    ["scissors", "paper"]
]

while True:
    user_input = input("Choose rock, paper, scissors, or quit ")
    challenge = user_input.lower()
    
    # 输入有效性校验,无效则重启循环
    if challenge not in valid_values:
        print("无效输入,请重新选择")
        continue
    
    # 处理退出指令
    if challenge == "quit":
        print("OK, bye")
        break
    
    # 执行游戏核心逻辑
    guess = random.choice(valid_values[:3])
    if challenge == guess:
        print("Tie!")
    elif [challenge, guess] in victories:
        print(f"The {challenge} beats the {guess}, you win!")
    else:
        print(f"The {guess} beats the {challenge}, you lose!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 15:12:12