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

如何在Python猜数字游戏的while循环中每次生成新随机数?

问题分析与解决方案

你的核心问题是初始随机数定义在循环外部,导致每次循环重启都复用同一个值,同时代码存在重复导入模块、变量作用域问题(比如random_number_two仅在"H"分支定义,选"L"会直接报错)。要实现不用每次新建变量生成新随机数,可以通过单个变量更新的方式解决。

关键修改点

  • 将初始随机数的生成移到while True循环内部,确保每次新局都重新生成第一个随机数。
  • 移除循环内重复的import random,模块仅需导入一次。
  • 用单个变量(如current_number)记录当前随机数,生成下一个数后可直接覆盖该变量,无需新建变量。
  • 统一处理"继续游玩"的逻辑,减少重复代码。

修改后的完整代码

import random

username = input("Greetings, what is your name? ")
start_game = input(f"Welcome to the number game, {username}!  Would you like to play a game? (Type 'Yes/No') ")

while True:
    if start_game.lower() == 'yes':
        # 每次新局生成第一个随机数
        current_number = random.randint(0, 100)
        print("Let's begin!")
        print(current_number)
        
        user_guess = input("Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: ").lower()
        
        if user_guess == 'h':
            print("You guessed higher. Let's see: ")
            current_number = random.randint(0, 100)
            print(current_number)
            print("You are correct! It was higher!" if current_number > prev_number else "You were wrong, it was lower.")
        elif user_guess == 'l':
            print("You guessed lower. Let's see: ")
            prev_number = current_number
            current_number = random.randint(0, 100)
            print(current_number)
            print("You are correct! It was lower!" if current_number < prev_number else "You were wrong, it was higher.")
        else:
            print("Invalid response. You Lose.")
            break
        
        # 统一处理继续游玩请求
        play_again = input("Would you like to play again? ('Yes'/'No') ").lower()
        start_game = play_again
        if play_again != 'yes':
            break
    elif start_game.lower() == 'no':
        print("Okay, maybe next time.")
        break
    else:
        print("Invalid response. You Lose.")
        break

额外优化说明

  • 使用.lower()统一转换输入为小写,避免重复判断'Yes'和'yes',简化代码。
  • 用f-string替代format(),让字符串拼接更直观。
  • 通过覆盖current_number变量实现新随机数的生成,完全无需每次新建变量。
  • 抽离"继续游玩"逻辑,减少代码冗余,提升可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:45:34