Concepts / Getting Input from Users: The input() Function

Getting Input from Users: The input() Function

A program may ask a user for a number, but the user can type something that is not a number.

  • Programming

When User Input Goes Wrong

A program may ask a user for a number, but the user can type something that is not a number. The input() function gives your program the user's response as a string. If the program then tries to convert that string into an integer and the conversion is impossible, Python raises a ValueError. Learning to handle this situation keeps the program from crashing and lets it give the user a useful response.

From Response to Integer

The data passes through two stages. First, input() receives the user's response as a string. Next, int() examines that string and attempts to produce an integer. If every character is valid for an integer, the conversion succeeds and int() returns a new integer value. If a character cannot be part of an integer, the conversion fails and Python raises a ValueError.

input()user responseStringfor example, 42int()conversionInteger42returnspassed toif valid
What type of data does input() produce, and how does that string become an integer when passed to int()?
python

In this example, response holds the string returned by input(). The call to int(response) attempts to convert that string into an integer. The conversion point is where a ValueError can occur.

Valid and Invalid Integer Strings

A string can be converted to an integer when it contains only digits, with an optional leading plus sign or minus sign. A string such as 42 represents an integer. A string such as hello does not represent an integer, so int() cannot complete the conversion and raises a ValueError.

42stringhellostring42integerValueErrorconversion failsint() succeedsint() raises
How does user input such as 42 differ from hello as it moves into int(), and where does conversion succeed or fail?
Input stringResult with int()
42Conversion succeeds
-7Conversion succeeds
+12Conversion succeeds
helloValueError
Other invalid contentValueError

Examples of strings that can or cannot represent integers

The same idea applies to float(). A float string may contain digits and at most one decimal point, with an optional leading sign. Letters, multiple decimal points, and other invalid content cause a ValueError during conversion.

What ValueError Means

Definition

ValueError is a runtime error that occurs when type conversion fails. For example, int() raises a ValueError when it tries to convert a string such as hello into an integer.

The error originates in the conversion function, not in input() itself. input() successfully provides a string. The problem appears when int() examines that string and finds content that cannot represent an integer. Without error handling, the ValueError crashes the program and displays an error message to the user.

python
Output (expected)
If the user enters hello, int(response) raises a ValueError.
Notes on the code
  • input() returns the user's response as a string.
  • int(response) attempts the conversion.
  • The invalid string causes the conversion to fail.

Redirecting Control with try/except

A try/except block places code that might fail inside a try block. The except ValueError block contains the response for a failed conversion. If no ValueError occurs, the conversion succeeds. If a ValueError occurs, Python moves from the try block to the except block, where the program can handle the problem instead of crashing.

input()receive stringint()try blockIntegerconversion succeedsValueErrorconversion failsexcept ValueErrorhandle errorstringvalidinvalidcontrol moves
What happens next when int() raises a ValueError, and how does control flow move from the try block to the except block?
Code walkthrough
try:
    response = input("Enter a whole number: ")
    number = int(response)
    print("Your number is", number)
except ValueError:
    print("Please enter a whole number.")
  1. 1
    Python enters the try block and calls input().
  2. 2
    The response is passed to int().
  3. 3
    For valid integer text, Python continues through the try block and prints the converted number.
  4. 4
    For invalid integer text, Python raises ValueError and moves to the except ValueError block.
  5. 5
    The except block prints a clear correction message instead of allowing the program to crash.
  • The try block contains the input and the conversion that might fail.
  • The conversion succeeds when the response represents an integer.
  • The except block runs only when a ValueError occurs.
  • The message tells the user what kind of input is expected.

Giving Users a Useful Recovery

Catching the error is only part of graceful handling. The except block should explain what went wrong and how the user can fix it. A program can then ask the user to try again or choose another sensible behavior. The important change is that invalid input is handled deliberately rather than crashing the program.

python

Here, a response such as 42 can be converted and stored in age. A response such as hello causes the except block to run. The message identifies the expected form of input, helping the user correct the problem.

Mistakes with Converted Input

  • Common mistake

    Assuming input() already returns a number

    What it looks like
    response = input("Enter a number: ")
    Why it fails

    input() returns a string, even when the user types digits.

    Do this instead

    Pass the response to int() or float() when a numeric value is needed.

  • Common mistake

    Converting user input without handling ValueError

    What it looks like
    number = int(input("Enter a number: "))
    Why it fails

    A response that cannot represent an integer causes a ValueError and can crash the program.

    Do this instead

    Put the conversion inside a try block and handle ValueError in an except block.

  • Common mistake

    Accepting every string as a valid integer

    What it looks like
    int("hello")
    Why it fails

    Letters and other invalid content cannot be converted into an integer.

    Do this instead

    Expect integer strings to contain digits, with an optional leading plus or minus sign.

  • Common mistake

    Giving an unclear error message

    What it looks like
    except ValueError:
        print("Error")
    Why it fails

    The user is not told what went wrong or how to correct the input.

    Do this instead

    Explain that the input must be a whole number or provide another clear correction.

Practice the Conversion Path

EASY

Write a short Python program that asks the user for a whole number, attempts to convert the response with int(), and prints a clear message if the conversion raises a ValueError.

Hints
  • Call input() to receive the response as a string.
  • Place int() inside the try block.
  • Use except ValueError for the failed conversion.
  • Make the error message explain what kind of input the user should enter.
Worked example

Tracing Two User Responses

Determine what happens when the conversion is given 42 and when it is given hello.

  1. 1
    Receive the response

    input() provides each user response as a string.

  2. 2
    Attempt conversion

    int() examines the string to determine whether it represents an integer.

  3. 3
    Process 42

    The string 42 contains digits, so the conversion succeeds and produces an integer.

  4. 4
    Process hello

    The string hello contains letters that cannot represent an integer, so int() raises a ValueError.

  5. 5
    Handle the failure

    When the conversion is inside try/except, control moves to except ValueError, where the program can print a correction message.

Result

Valid integer text continues with a converted integer. Invalid text is handled by the except ValueError block instead of being left as an unhandled conversion failure.

Key Takeaways

  1. 1
    input() returns the user's response as a string.
  2. 2
    int() and float() convert strings into numeric types when the string has a valid form.
  3. 3
    int() raises a ValueError when the string cannot represent an integer.
  4. 4
    A try/except block catches ValueError and lets the program respond without crashing.
  5. 5
    Clear messages in the except block help users understand how to correct invalid input.

At a glance

  • input() produces strings, not numeric values.
  • Integer conversion succeeds for digits and an optional leading plus or minus sign.
  • Invalid conversion input causes int() to raise a ValueError.
  • try/except redirects control to an error-handling block when conversion fails.
  • Clear recovery messages create a better response to unpredictable user input.

Related concepts

More concepts starting with G