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

Python开发Higher or Lower猜数字游戏无法更新基准数问题求助

问题根源

你把基准数初始化代码first_number = 11放在了while循环的第一行,这会导致每一轮循环启动时,不管上一轮猜对后你把first_number改成了什么值,都会被强制重置为11,自然无法继承上一轮的正确结果作为新基准。

修复步骤
  • 第一步:把first_number = 11从while循环内部移到循环外,放在end_of_game = False的下一行,作为全局初始基准值。
  • 第二步:在所有玩家猜错的逻辑分支里,除了重置streak为0,也要同步把first_number重置为11,符合你设定的「输了就从11重新开始」的规则。
  • 额外注意:代码开头需要先导入random模块,否则调用random.randint会报错。
修改后可正常运行的代码
import random
# 如果你有自己写的artwork模块就保留这行,没有可以注释掉
# import artwork

streak = 0
# print(artwork.title)
print("Welcome to High or Low!\nDo you think the next number will be higher or lower?")
print("\nThe game always starts with the number 11, get a streak of 5 to win!")
end_of_game = False
# 基准数初始化移到循环外,仅执行一次
first_number = 11

while not end_of_game:
    second_number = random.randint(1, 21)
    player_input = input("\nHigher or Lower? Type H or L\n").lower()

    if player_input == "h" and second_number > first_number:
        streak += 1
        print(f"{second_number} Correct!")
        first_number = second_number
        print(f"Current Streak is: {streak}")
        print(f"\n\nThe current number is: {first_number}")
        if streak == 5:
            print("Congratulations YOU WIN!")
            end_of_game = True
    elif player_input == "l" and second_number < first_number:
        streak += 1
        print(f"{second_number} Correct!")
        first_number = second_number
        print(f"Current Streak is: {streak}")
        print(f"\n\nThe current number is: {first_number}")
        if streak == 5:
            print("Congratulations YOU WIN!")
            end_of_game = True
    else:
        # 合并所有猜错的分支,简化代码结构
        print(f"{second_number}, Unlucky")
        print("\nTry again, the number is 11")
        streak = 0
        # 猜错同步重置基准数
        first_number = 11

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 03:42:03