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

猜数字游戏Python代码运行逻辑异常问题咨询

问题分析与修复

问题根源

你代码里的核心问题是每次循环都会重新生成随机目标数字——random.randint(1,10)被放在了while循环内部,导致用户每猜一次,正确答案就换了一个。这就解释了为什么你根据提示猜6时,结果还是不对:因为这次的目标数字已经不是之前那个了。

修复后的代码

import random
print("lets play the game")
print("you will be given 3 chances to play the game")
i = 1
score = 0

# 把目标数字生成移到循环外,确保3次机会猜同一个数
c = random.randint(1, 10)

while(i <= 3):
    d = int(input("enter your choice: "))
    if(d == c):
        score += 1
        print("congrats it was the correct guess")
        print(f"you have {3 - i} chances left +1")
    elif(d > c):
        print(" oops !!your choice was too high")
        print(f"you have {3 - i} chances left,better luck next time")
    elif(d < c):
         print(" oops !!your choice was too low")
         print(f"you have {3 - i} chances left,better luck next time")
    i += 1

print(f"your score is {score}")

修复说明

把c = random.randint(1,10)移到while循环之前后,整个游戏的3次机会都会围绕同一个固定的目标数字进行,用户根据前一次的提示(过高/过低)调整猜测时,逻辑就完全通顺了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 11:20:37