How to Validate Integer Input in Python
Accepting user input in Python using input() always returns a string. If you need to perform mathematical operations, you must convert this string into an integer. However, if the user types letters or special characters, a direct conversion will crash the program.
This guide explains how to validate integer input safely using try-except blocks, how to handle negative numbers (which string methods often miss), and how to create a robust "retry until valid" loop.
The Basic Conversion Error
The standard way to convert inputs is using the int() constructor. However, this function is strict; it raises a ValueError if the string contains anything other than digits (and potentially a leading sign).
# ⛔️ Error: This crashes if the user types "abc" or "12.5"
user_input = "five"
number = int(user_input)
print(f"Your number is {number}")
Output:
ValueError: invalid literal for int() with base 10: 'five'
Method 1: Using try-except (Recommended)
The most robust, "Pythonic" way to validate input is to attempt the conversion and catch the error if it fails. This handles standard integers, negative numbers, and ignores whitespace automatically.
user_input = " -42 " # Note the spaces
try:
# ✅ Solution: Attempt conversion and catch errors
value = int(user_input)
print(f"Valid integer: {value}")
except ValueError:
print("Invalid input. Please enter a whole number.")
Output:
Valid integer: -42
Handling Floats
Note that int() will fail on strings containing decimals (e.g., "5.5"). If you want to accept floats and truncate them to integers:
user_input = "5.9"
try:
# ✅ Convert to float first, then int
value = int(float(user_input))
print(f"Converted integer: {value}")
except ValueError:
print("Invalid numeric input.")
Output:
Converted integer: 5
Method 2: Using String Methods (isdigit)
You can check if a string contains only digits using .isdigit(). While simple, this method has a significant limitation: it does not accept negative numbers because the minus sign - is not a digit.
# Case A: Positive Integer
input_a = "100"
if input_a.isdigit():
print(f"'{input_a}' is a valid digit string.")
else:
print(f"'{input_a}' is invalid.")
# Case B: Negative Integer
input_b = "-50"
# ⛔️ Limitation: Returns False for negative numbers
if input_b.isdigit():
print(f"'{input_b}' is a valid digit string.")
else:
print(f"'{input_b}' is rejected by isdigit().")
Output:
'100' is a valid digit string.
'-50' is rejected by isdigit().
Avoid using .isdigit() or .isnumeric() for general integer validation if your application needs to support negative values or whitespace padding. The try-except method is safer.
Method 3: Implementing a Retry Loop
In real-world command-line applications, you typically want to prevent the program from crashing and ask the user again until they provide valid input.
Use a while True loop combined with try-except and break.
def get_valid_integer(prompt):
while True:
user_input = input(prompt)
try:
# ✅ Solution: Convert, check logic, then break
value = int(user_input)
# Optional: Add range validation
if value < 0:
print("Please enter a positive integer.")
continue
return value
except ValueError:
print(f"Error: '{user_input}' is not a valid number. Try again.")
# usage (Simulated input)
age = get_valid_integer("Enter your age: ")
print(f"Success! Age recorded as: {age}")
Output (Scenario where user types "twenty" then "25"):
Enter your age: twenty
Error: 'twenty' is not a valid number. Try again.
Enter your age: 25
Success! Age recorded as: 25
This pattern is robust because it handles the control flow entirely within the function, keeping your main application logic clean.
Conclusion
To validate integer input in Python effectively:
- Use
try-except ValueErroras your primary validation tool. It supports negative numbers and whitespace correctly. - Avoid
isdigit()unless you are strictly validating identifiers like PIN codes or Phone numbers where signs are not allowed. - Wrap logic in a
whileloop to allow users to correct their mistakes without restarting the program.