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

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 random module import: Without import random at the top, Python won't recognize random.randint, which is definitely throwing a NameError when 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 if block: Your loop only runs when the numbers don’t match, so the if number_to_guess == my_number check inside the loop will never execute.
  • No exit handling: You never added logic to check if the user entered 0 and 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 random to fix the initial NameError.
  • Switched to an infinite while True loop for better control over exit conditions (either on 0 or correct guess).
  • Added a try/except block to handle non-numeric inputs, so the game won’t crash if someone types a letter instead of a number.
  • Checks for 0 immediately 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 else clause (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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:54:07