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

Python开发石头剪刀布游戏时while循环无法重复执行问题

问题排查结果

你的循环无法重复执行的核心原因有3个:

  • while循环的每个胜负/平局分支都写了return语句,Python中函数一旦执行return就会立即终止运行返回结果,第一回合跑完就直接退出了play函数,根本不会进入下一轮循环判断。
  • 你将胜场、回合数作为参数传入play函数,整数属于不可变类型,函数内修改的是参数的局部副本,就算循环正常运行也无法正确累计全局的计数结果。
  • 电脑最终获胜的分支只写了字符串"The computer won",没有加return关键字,走到该分支时不会返回任何内容。
修复后完整可运行代码
import random

def is_win(player, opponent):
    if (player == 'r' and opponent == 's') or (player == 's' and opponent == 'p') \
        or (player == 'p' and opponent == 'r'):
        return True

def play():
    computer_win = 0
    user_win = 0
    jugadas = 0
    while jugadas < 3:
        user = input("What's your choice? 'r' for rock, 'p' for paper, 's' for scissors: ")
        # 输入合法性校验,避免非法输入计入回合数
        if user not in ('r', 'p', 's'):
            print("Invalid input, please enter 'r', 'p' or 's'")
            continue
        computer = random.choice(['r','p','s'])        
        if user == computer:
            jugadas += 1
            print(f'It\'s a tie. Round {jugadas}/3')
        elif is_win(user, computer):
            user_win += 1
            jugadas += 1
            print(f'You won! Round {jugadas}/3')
        else:
            computer_win += 1
            jugadas += 1
            print(f'You lost! Round {jugadas}/3')

    # 3回合全部结束后再判断最终胜负返回结果
    if computer_win > user_win:
        return "The computer won the game"
    elif user_win > computer_win:
        return "You won the game!"
    else:
        return "It's a tie ...."

print(play())
关键修改说明
  • 移除了循环内部所有分支的return语句,每回合结束后仅打印当前回合结果、更新计数,不会提前终止函数,循环会自动进入下一轮直到打满3回合。
  • 把胜场、回合计数变量直接放在play函数内部初始化,避免传值导致的计数不累计问题。
  • 补全了电脑获胜分支的返回逻辑,修复无返回值的bug。
  • 新增了简单的输入校验,用户输入非指定内容时不会消耗回合数,会提示重新输入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 01:45:36