How to take integer input in Python?

Published on Aug. 22, 2023, 12:15 p.m.

To take integer input in Python, you can use the input() function to read the user’s input as a string first, and then use the int() function to convert the string to an integer. Here’s an example:

num = int(input("Enter an integer: "))
print("You entered:", num)

In this example, the input() function reads the user’s input as a string, and the int() function is used to convert the string to an integer. The resulting integer is then stored in the num variable, and printed using the print() function.

Note that if the user enters anything other than an integer, such as a string or a decimal number, the program will throw a ValueError. To handle this, you can use a try-except block to catch the error and handle it appropriately. Here’s an example:

try:
    num = int(input("Enter an integer: "))
    print("You entered:", num)
except ValueError:
    print("Invalid input. Please enter an integer.")

This example uses a try-except block to catch the ValueError that’s raised if the user enters anything other than an integer. If a ValueError is caught, the program will print an error message and prompt the user to enter an integer again.

Tags:

related content