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

Python猜数字游戏最后一次猜对无恭喜提示问题求助

猜数字游戏最后一次猜对不显示恭喜信息的问题解决

你的代码问题出在第5次输入的数字根本没进入判断逻辑:

  • 初始count=0,循环条件是count <=3,这意味着循环只会执行4次(count从0到3)
  • 第5次输入的n是在循环结束后才获取的,程序直接跳过判断,执行print("The Game ist Over!"),所以猜对了也不会触发恭喜语句

修复方案(推荐结构更清晰的写法)

调整循环逻辑,把输入放到循环内部,确保每一次尝试都能被判断,同时用while-else区分“猜对结束”和“用完次数结束”的场景:

from random import randint

x = randint(1, 20)  
# print(x)  # 测试时可以打开看答案,正式版建议注释
max_tries = 5
count = 0  

print(f"Guessing Game! You have {max_tries} tries to guess a number between 1 and 20!")  

while count < max_tries:
    n = int(input("Enter your number: "))
    count += 1
    remaining_tries = max_tries - count
    
    if n < x:
        print(f"{n} is smaller. You have {remaining_tries} tries left")
    elif n > x:
        print(f"{n} is greater. You have {remaining_tries} tries left")
    else:
        print("Congrats. You guessed the correct number")
        break
else:
    # 只有当循环正常结束(没触发break),才显示游戏结束
    print("The Game is Over!")

关键修改点

  1. 将输入语句移到循环内部,保证5次尝试都能进入判断流程
  2. 用max_tries变量统一管理尝试次数,逻辑更直观,后续修改次数只需改这个变量
  3. while-else结构:当玩家猜对触发break时,不会执行else块的游戏结束提示;只有用完所有尝试没猜对时,才显示游戏结束

基于原代码的快速修复

如果不想大改结构,也可以在循环结束后补一次判断:

from random import randint

x = randint(1, 20)  
print(x)  
count = 0  
t = str(4 - count)  
print("Guessing Game! You have 5 tries to guess a number between 1 and 20!")  
n = int(input("Enter your number: "))

while count <= 3:
    if n < x:
        print(f"{n} is smaller. You have {t} tries left")
    elif n > x:
        print(f"{n} is greater. You have {t} tries left")
    else:
        print("Congrats. You guessed the correct number")
        break
    count += 1
    t = str(4 - count)
    # 只有还有剩余次数时才输入新数字
    if count <= 3:
        n = int(input("Enter your number: "))

# 循环结束后判断最后一次输入是否正确
if n == x:
    print("Congrats. You guessed the correct number")
else:
    print("The Game is Over!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:57:17