Skip to content

How to take integer input in Python 3 | Example code

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:

How to take integer input in Python 3

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.

3 thoughts on “How to take integer input in Python 3 | Example code”

Leave a Reply

Your email address will not be published. Required fields are marked *