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

Python猜谜游戏问题:猜对后仍触发提示语句的解决求助

猜谜游戏提示异常问题修复

核心问题:提示输出逻辑未与「猜错」操作绑定,无论猜对猜错都会执行提示代码,导致猜对时仍显示不必要的提示。

修改后的代码

secret_w = "giraffe"
guess= ""
guess_remain = 3
guess_c = 0
guess_limit = 2
outofguesses = False

while guess != secret_w and not(outofguesses):
    guess = input("I'm thinking of an animal, try and guess it!  ")
    guess_c += 1
    if guess != secret_w:
        print("Incorrect, try again")
        guess_remain -= 1
        print("You've guessed", guess_c, "times and have", guess_remain, "guesses left!")
        
        # 仅在猜错时触发提示
        if guess_c == 1:
            print("Hint 1: It's tall!")
        if guess_c == 2:
            print("Hint 2: It has spots and a long neck")

    if guess_c > guess_limit:
        outofguesses = True

if outofguesses:
    print("You're out of guesses, better luck next time!")

if guess == secret_w:
    print("Well done")
    print("You got it on attempt number", guess_c )

修改说明

将两个提示输出的if判断语句,移动到if guess != secret_w:的代码块内部。这样只有当用户猜错时,才会根据当前的猜测次数显示对应提示;如果猜对,会直接跳过这段提示逻辑,符合预期效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:15:28