猜数字游戏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
相关产品推荐
相关产品推荐

