Python猜数字游戏退出功能开发求助:输入0无法正常触发退出
Fixing Your Number Guessing Game with Exit Functionality
Let's walk through the issues in your code and fix them step by step to get that exit-on-0 feature working properly, plus squash those other bugs you might not have noticed yet!
Key Bugs in Your Original Code
- Missing
randommodule import: Withoutimport randomat the top, Python won't recognizerandom.randint, which is definitely throwing aNameErrorwhen you run the code. - Reversed "higher/lower" hints: If
number_to_guess > my_number, that means the user’s guess is too small—your original code told them their number "must be higher", which is confusing and backwards. - Useless final
ifblock: Your loop only runs when the numbers don’t match, so theif number_to_guess == my_numbercheck inside the loop will never execute. - No exit handling: You never added logic to check if the user entered
0and trigger an exit.
Fixed Full Code with Exit Functionality
import random # Critical missing import! print("I guessed a number, try to find it") number_to_guess = random.randint(1, 9999) number_of_tries = 0 while True: # Get input and validate it first guess_input = input("Guess the number (enter 0 to quit): ") # Handle non-numeric inputs to avoid crashes try: my_number = int(guess_input) except ValueError: print("Oops, please enter a valid number!") continue number_of_tries += 1 # Check for exit condition first if my_number == 0: print("You've exited the game. Thanks for playing!") break # Give correct hint based on guess if my_number < number_to_guess: print("Too low! Try a higher number.") elif my_number > number_to_guess: print("Too high! Try a lower number.") else: # Correct guess! print(f"Congrats, you guessed the number in {number_of_tries} tries!") break
What We Changed & Why
- Added
import randomto fix the initial NameError. - Switched to an infinite
while Trueloop for better control over exit conditions (either on0or correct guess). - Added a
try/exceptblock to handle non-numeric inputs, so the game won’t crash if someone types a letter instead of a number. - Checks for
0immediately after validating the input, then prints a clear exit message and breaks the loop. - Fixed the hint text to be intuitive and correct.
- Simplified the win condition to an
elseclause (if the guess isn’t too high or too low, it must be a match). - Cleaned up the try counter to increment for every valid guess, including the winning one.
This code will run without errors, properly handle the exit-on-0 request, and play the number guessing game as intended!
内容的提问来源于stack exchange,提问作者user14780324
相关产品推荐
相关产品推荐

