How to take Integer user input in Python
Collecting integer input from users is a common requirement in interactive Python applications.
This guide explores various methods for obtaining integer input, including input validation, error handling, and range checking, allowing you to ensure your programs receive valid integer values.
Basic Integer Input with int()
The most basic approach to take integer input is by using the input()
function to get a string from the user, and then immediately converting that string into an integer using the int()
constructor:
user_input = int(input('Enter an integer: '))
print(user_input)
The input()
function always returns a string. The int()
constructor then attempts to convert the returned string to an integer.
Handling ValueError
Exceptions
If the user enters a non-numeric string that can not be converted to an integer, the int()
constructor raises a ValueError
. Use a try
/except
block to handle this situation:
try:
user_input = int(input('Enter an integer: '))
print(user_input)
except ValueError:
print('Enter a valid integer')
- The
try
block contains the code which can potentially throw an exception. - The
except ValueError
block handles theValueError
exception, if the user types non numeric characters.
Validating Input with a Loop
To ensure that the user only enters a valid integer, embed the try
/except
block in a while
loop:
while True:
try:
num = int(input('Your favorite integer: '))
print(num)
break
except ValueError:
print('Please enter an integer.')
Explanation:
- The
while True
loop continues to ask for input until a valid integer is entered. - If
int(input())
throws a ValueError, the except block is executed, an error message is printed and the loop continues with thecontinue
statement. - If the conversion is successful, the integer is printed and the loop is terminated using
break
.
Limiting Input to a Specific Range
You can add a range check using an if
statement inside the try
block, or you can raise your own ValueError
when the number is out of range:
while True:
try:
num = int(input('Integer between 1 and 100: '))
print(num)
if not 1 <= num <= 100:
raise ValueError
break
except ValueError:
print('Please enter an integer between 1 and 100.')
Explanation:
- The
while
loop will continue to prompt the user for input until the user enters a valid integer within range. - If the
int(input())
throws aValueError
or the if condition is met, the except block is executed, an error message is printed and the loop continues. - If the input is valid, the integer is printed and the loop breaks using the break keyword.