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

Python猜数字游戏问题:选择NO后重复启动如何修复?

问题分析与修复

你的问题出在递归调用后的while循环逻辑:当你输入"yes"进入循环后,调用guessing_game_func()开启新游戏,但新游戏结束后,原循环的decision值仍然是"yes",会再次触发函数调用;而当你在新游戏中选择"no"时,只是当前递归层打印"Close IDE",但上层的循环还会继续执行,导致游戏重启。

同时原代码还有一个小语法错误:print语句中拼接字符串时缺少换行处理,导致提示信息无法正常显示。


修复方案(推荐用循环替代递归,避免嵌套问题)

把游戏的重复运行逻辑放在外层循环中,不再用递归调用,流程更清晰,也不会出现嵌套后的返回问题:

import random
import math

def guessing_game_func():
    name = input("Enter your name: ")
    print("Welcome ", name)
    lower_bound = 0
    upper_bound = 50
    # 生成0到50之间的随机数
    random_number = random.randint(lower_bound, upper_bound)
    min_guessing_num = int(math.log(upper_bound - lower_bound + 1, 2))
    # 修复字符串换行问题
    print("INSTRUCTION: Guess a number between 0 and 50\nHOT means you are close to the correct number and COLD means you are far from it")
    print("You have only ", round(min_guessing_num), "tries")

    # 初始化猜测次数
    count = 0
    while count < min_guessing_num:
        count += 1
        guess = int(input("Guess a number: "))
        if random_number == guess:
            print("Congratulations. You guessed correctly after", count, "tries")
            break
        elif random_number > guess:
            print("Hot")
        elif random_number < guess:
            print("Cold")

        if count >= min_guessing_num:
            print("Fail! The number is", random_number)

# 外层循环控制游戏是否继续
while True:
    guessing_game_func()
    decision = input("Do you wish to play again? YES or NO").lower()
    if decision != "yes":
        print("Close IDE")
        break

另一种修复(保留递归)

如果你想继续用递归,只需把原来的while循环改成if判断,避免重复触发递归:

修改原代码中决策部分的代码:

decision = input("Do you wish to play again? YES or NO").lower()
    if decision == "yes":
        guessing_game_func()
    elif decision == "no":
        print("Close IDE")

同时记得修复print语句的换行问题:

print("INSTRUCTION: Guess a number between 0 and 50\nHOT means you are close to the correct number and COLD means you are far from it")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:05:17