Use Python built-in input() function to take integer input from the user. This input() function returns string data and it can be stored in a string variable. Then use the int() function to parse into an integer value.
num = int(input("Enter an integer: "))
Example take integer input in Python 3
In a simple example code taking integer input, we have to typecast those inputs into integers by using Python’s built-in int() function.
age = int(input("Enter age: "))
print(age)
print(type(age))
Output:
Keep in mind that if the user enters a non-integer value, such as a string or a floating-point number, a ValueError
will be raised. To handle this, you can wrap the input statement in a try-except
block. Here’s an example:
try:
num = int(input("Enter an integer: "))
# Rest of your code using the integer input
except ValueError:
print("Invalid input. Please enter an integer.")
In this case, if the user enters a non-integer value, a ValueError
will be caught by the except
block, and an error message will be displayed.
Do comment if you have any doubts or suggestions on this Python input code.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Some online examples use eval instead of int, but this is dangerous, as eval can execute malicious python code if input.
It doesn’t work for me on python 3. I don’t know why.
Make sure there are parentheses at the end of the line