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
whileloop has a logic bug: if you guess right on your first attempt (count = 0), it will run infinitely becausecount <=0stays true aftercount = count -1turns 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:
- Removed the unwanted final print statement: We replaced it with an
if/elsecheck, 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. - Fixed the infinite loop: The second
whileloop now runs only whencount > 0, so it stops automatically oncecounthits 0 (printing the message exactly as many times as you guessed wrong). - Simplified code: Used
count +=1instead ofcount = 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). - Better initial guess value: Set
guess = ""instead of0to avoid accidental type mismatch issues—sinceinput()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
相关产品推荐
相关产品推荐

