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

Python猜数字程序:输入Exit退出While循环报错求助

Fixing the Input Error in Your Number Guessing Game

Hey Sherry, great job working on your number guessing assignment—let's get that input issue sorted out quickly!

The Root of the Problem

The error happens because when a user types "Exit" (or any non-numeric string), you're trying to convert it directly to an integer with int(input(...)). Python can't turn a word like "Exit" into a number, so it throws a ValueError every time someone tries to quit.

How to Fix It

We need to split up the input handling: first capture the raw input as a string, check if the user wants to exit, then safely convert to an integer only if it's a valid number. Here's a step-by-step solution with full code:

  1. Capture raw input first: Don't convert to int immediately—store the user's input as a string so we can check for "Exit".
  2. Handle the exit condition first: Check if the input matches "Exit" (we'll make it case-insensitive so "exit" or "EXIT" works too).
  3. Safely convert to integer: Use a try-except block to catch cases where the user enters something that's not a number (like typos), so your program doesn't crash.

Working Example Code

import random

# Generate your random number between 1-9
secret_num = random.randint(1, 9)

while True:
    # Get raw input as a string
    user_input = input("Guess a number from 1 to 9, or type 'Exit' to quit: ").strip()
    
    # Check if user wants to exit
    if user_input.lower() == "exit":
        print("Thanks for playing! See you later.")
        break
    
    # Try converting to integer and handle errors
    try:
        guess = int(user_input)
        # Add your number guessing logic here
        if guess == secret_num:
            print("You got it! Great guess!")
            break
        elif guess < secret_num:
            print("Too low—give it another shot!")
        else:
            print("Too high—try a smaller number!")
    except ValueError:
        print("Oops, that's not a valid input. Please enter a number 1-9 or 'Exit' to quit.")

Why This Works

  • By checking for "Exit" before trying to convert to an integer, we avoid the conversion error entirely when the user wants to quit.
  • The try-except block catches any other non-numeric inputs (like "abc" or "100") and gives a friendly error message instead of crashing the program.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:11:11