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

Python循环代码优化需求:移除猜中后的错误次数统计输出

Fixing Your Age-Guessing Game Output Logic

Hey there! Let's get your Python age-guessing game working exactly how you want it. I see two main things to fix: removing that unwanted wrong-count message after a correct guess, and cleaning up the output logic overall. Here's how to do it step by step:

First, let's break down the issues in your original code:

  • The final print("You guessed wrong this many times:{1} ".format(count)) runs every single time—even when you guess correctly on the first try. That's the line we need to eliminate or conditionally hide.
  • The second while loop has a logic bug: if you guess right on your first attempt (count = 0), it will run infinitely because count <=0 stays true after count = count -1 turns it into -1, -2, and so on.

Here's the revised code with all fixes applied:

import time

age = input("How old? ")
guess = ""
count = 0

while guess != age:
    guess = input("What's your guess? ")
    if guess == age:
        print("Correct!")
    else:
        print("Wrong!")
        count += 1  # Shorter, more Pythonic way to write count = count + 1

# Only display wrong guess count if there were actual mistakes
if count > 0:
    print(f"You guessed wrong {count} times.")
else:
    print("Wow, you nailed it on the first try! No wrong guesses at all.")

# Fixed loop to show "messed up" message exactly as many times as there were wrong guesses
while count > 0:
    print(f"You messed up this many times: {count}")
    count -= 1

time.sleep(5)

Key changes explained:

  1. Removed the unwanted final print statement: We replaced it with an if/else check, so the wrong guess count only shows up when you actually made mistakes. If you get it right on the first try, you get a positive, encouraging message instead.
  2. Fixed the infinite loop: The second while loop now runs only when count > 0, so it stops automatically once count hits 0 (printing the message exactly as many times as you guessed wrong).
  3. Simplified code: Used count +=1 instead of count = count +1 (a common Python shorthand) and switched to f-strings for cleaner, easier-to-read string formatting (works in Python 3.6 and above).
  4. Better initial guess value: Set guess = "" instead of 0 to avoid accidental type mismatch issues—since input() returns a string, comparing a number to a string would never match otherwise.

This setup gives you the clean, logical output you're looking for—no more unwanted messages, and the loop behavior makes perfect sense now!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:11:12