Home »
Python
Asking (Limit) the user for only integer input in Python
By IncludeHelp Last updated : December 08, 2024
Input an integer value
input() function can be used for the input, but it reads the value as a string, then we can use the int() function to convert string value to an integer.
Consider the below program,
# input a number
num = int(input("Enter an integer number: "))
print("num:", num)
Output
RUN 1:
Enter an integer number: 10
num: 10
RUN 2:
Enter an integer number: 12.5
Traceback (most recent call last):
File "main.py", line 2, in <module>
num = int(input("Enter an integer number: "))
ValueError: invalid literal for int() with base 10: '12.5'
RUN 3:
Enter an integer number: Hello
Traceback (most recent call last):
File "main.py", line 2, in <module>
num = int(input("Enter an integer number: "))
ValueError: invalid literal for int() with base 10: 'Hello'
See the output – the program works fine if we input an integer value (RUN 1), but if we input other than integer (RUN 2, RUN3) program returns a ValueError.
Handle exception while reading an integer value
To handle ValueError, we can use a try-except statement.
See the below program,
# input a number
try:
num = int(input("Enter an integer number: "))
print("num:", num)
except ValueError:
print("Please input integer only...")
Output
RUN 1:
Enter an integer number: 10
num: 10
RUN 2:
Enter an integer number: 12.5
Please input integer only...
RUN 3:
Enter an integer number: Hello
Please input integer only...
See the output – the program works fine if we input an integer value (RUN 1), but if we input other than integer (RUN 2, RUN3) program's control transferred to the except block and printed our message. Here, we have handled the exception but still, our task is not completed.
Input until a valid integer value is not entered
We need to take input until a valid integer value is not entered. For that, we will use while True (for an infinite loop) and will be taking the input till the valid integer.
See the below program,
Python program for limiting the user to input only integer value
# input a number
while True:
try:
num = int(input("Enter an integer number: "))
break
except ValueError:
print("Please input integer only...")
continue
print("num:", num)
Output
Enter an integer number: 12.5
Please input integer only...
Enter an integer number: Hello world
Please input integer only...
Enter an integer number: Ten
Please input integer only...
Enter an integer number: Twenty Four
Please input integer only...
Enter an integer number: 24
num: 24
Finally, we did it. By using this method we can set the limit to the user to input/accept only integers.