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

Python石头剪刀布游戏结果异常问题求助

问题排查与修复

核心错误点

  1. 输入类型不匹配
    input()函数返回的是字符串,比如用户输入1,变量user实际是"1"(字符串类型),但代码里用user == 1(整数)做比较,所有条件都无法触发,导致每个while True循环无限运行。

  2. 冗余且错误的循环结构
    三个独立的while True会依次执行,哪怕第一个循环已经输出结果,程序仍会进入后续循环,逻辑完全混乱。

修复后的代码

import random

# 石头剪刀布列表
knb = ["stone", "scissors", "paper"]

print('Welcome to the familiar "Rock, Paper, Scissors" game! The rules are quite simple and I think everyone understands. Today your opponent will be a computer.')
print('Here we go! If you want to choose a stone, enter the number "1", for scissors and paper "2" and "3" respectively.')

comp = random.choice(knb)

# 转换输入为整数,同时处理无效输入
while True:
    try:
        user = int(input('Please choose. Stone, scissors or paper? '))
        if user not in [1,2,3]:
            print("Invalid input! Please enter 1, 2 or 3.")
            continue
        break
    except ValueError:
        print("Please enter a valid number!")

# 结果判断,整合为一个逻辑块
if (comp == "stone" and user == 1) or (comp == "scissors" and user == 2) or (comp == "paper" and user == 3):
    print(f"Tie! The computer picked {comp}")
elif (comp == "stone" and user == 3) or (comp == "scissors" and user == 1) or (comp == "paper" and user == 2):
    print(f"You win! The computer has chosen {comp}")
elif (comp == "stone" and user == 2) or (comp == "scissors" and user == 3) or (comp == "paper" and user == 1):
    print(f"You lose! The computer has chosen {comp}")

关键修改说明

  • 将用户输入转换为整数类型,并添加输入验证,避免无效输入导致的错误。
  • 把所有结果判断整合到一个逻辑块中,不再使用多个独立循环,确保只会输出一个对应结果。
  • 修正了提示文本里的"letter"为"number"(因为要求用户输入的是数字1/2/3)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:11:07