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.
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.
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.
| Input string | Result with int() |
|---|---|
| 42 | Conversion succeeds |
| -7 | Conversion succeeds |
| +12 | Conversion succeeds |
| hello | ValueError |
| Other invalid content | ValueError |
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.
If the user enters hello, int(response) raises a ValueError.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.
try:
response = input("Enter a whole number: ")
number = int(response)
print("Your number is", number)
except ValueError:
print("Please enter a whole number.")- 1Python enters the try block and calls
input(). - 2The response is passed to
int(). - 3For valid integer text, Python continues through the try block and prints the converted number.
- 4For invalid integer text, Python raises
ValueErrorand moves to the exceptValueErrorblock. - 5The 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
ValueErroroccurs. - 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.
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 likeresponse = input("Enter a number: ")Why it failsinput()returns a string, even when the user types digits.Do this insteadPass the response to int() or float() when a numeric value is needed.
Common mistake Converting user input without handling ValueError
What it looks likenumber = int(input("Enter a number: "))Why it failsA response that cannot represent an integer causes a
ValueErrorand can crash the program.Do this insteadPut 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 likeint("hello")Why it failsLetters and other invalid content cannot be converted into an integer.
Do this insteadExpect integer strings to contain digits, with an optional leading plus or minus sign.
Common mistake Giving an unclear error message
What it looks likeexcept ValueError: print("Error")Why it failsThe user is not told what went wrong or how to correct the input.
Do this insteadExplain that the input must be a whole number or provide another clear correction.
Practice the Conversion Path
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
ValueErrorfor 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.
- 1Receive the response
input()provides each user response as a string. - 2Attempt conversion
int()examines the string to determine whether it represents an integer. - 3Process 42
The string 42 contains digits, so the conversion succeeds and produces an integer.
- 4Process hello
The string hello contains letters that cannot represent an integer, so
int()raises aValueError. - 5Handle 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()andfloat()convert strings into numeric types when the string has a valid form. - 3
int()raises aValueErrorwhen the string cannot represent an integer. - 4A try/except block catches
ValueErrorand lets the program respond without crashing. - 5Clear 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 aValueError. - try/except redirects control to an error-handling block when conversion fails.
- Clear recovery messages create a better response to unpredictable user input.