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

Python猜数字游戏无法重新生成随机整数问题求助

解决猜数字游戏重玩时随机数不更新的问题

问题根源

你代码里的Replay()函数中定义的num是局部变量,和全局作用域的num不是同一个变量,所以Game()调用时始终使用最初生成的全局随机数,不会更新。另外递归调用Game()和Replay()存在栈溢出风险,更推荐用循环结构实现。

方案1:修改全局变量(适配现有代码)

在Replay()中用global关键字声明要修改全局变量,这样新生成的随机数会覆盖全局的num:

import random
num = random.randint(0,100)

def Game():
    print("Guess the Number: ")
    guess = int(input())
    if guess == num:
        print("CORRECT!!!!!")
        Replay()
    elif guess > num:
        print("Sorry too high... Try again")
        Game()
    elif guess < num:
        print("Sorry too low... Try Again")
        Game()

def Replay():
    global num  # 声明操作全局变量
    num = random.randint(0,100)
    Game()

Replay()

方案2:重构为循环结构(更规范健壮)

放弃全局变量和递归,每个游戏周期独立生成随机数,用while循环实现游戏逻辑和重玩流程,还能添加输入合法性检查:

import random

def play_game():
    # 每个新游戏生成独立的随机数
    num = random.randint(0, 100)
    while True:
        print("Guess the Number: ")
        # 处理非整数输入
        try:
            guess = int(input())
        except ValueError:
            print("请输入有效的整数!")
            continue
        
        if guess == num:
            print("CORRECT!!!!!")
            break
        elif guess > num:
            print("Sorry too high... Try again")
        elif guess < num:
            print("Sorry too low... Try Again")

# 循环实现重玩
while True:
    play_game()
    # 可选:询问用户是否继续
    # choice = input("再玩一次?(y/n): ").strip().lower()
    # if choice != 'y':
    #     break

内容的提问来源于stack exchange,提问作者James G.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 22:45:29