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

Getting Input from Users: The input() Function

ValueError is a runtime error that occurs when type conversion fails—for example, when int() tries to convert a string like 'hello' to an integer.

  • 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.

returnspassed toif validinput()user responseStringfor example, 42int()conversionInteger42
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.

int() succeedsint() raises42stringhellostring42integerValueErrorconversion fails
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

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.

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.

stringvalidinvalidcontrol movesinput()receive stringint()try blockIntegerconversion succeedsValueErrorconversion failsexcept ValueErrorhandle error
What happens next when int() raises a ValueError, and how does control flow move from the try block to the except block?

try: response = input("Enter a whole number: ") number = int(response) print("Your number is", number) except ValueError: print("Please enter a whole number.")

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

  • Assuming input() already returns a number

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

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

  • Converting user input without handling ValueError

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

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

  • Accepting every string as a valid integer

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

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

  • Giving an unclear error message

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

    Fix: 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.

Tracing Two User Responses

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

Receive the response: input() provides each user response as a string.

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

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

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

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

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

Key Takeaways

  • 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.