How to take input as int (integer) in python?

In this short article, we will learn how to make the input function accept only integers as input values in python.

The input() function in python is used to take user data as input. It prompts for input when we run the program and reads the line.

It reads the user input from the prompt and returns a string. So, whatever the user enters, whether it be a number, text, or boolean all will be converted into a string in input() function.

We can check the data type of the input data using type() function.

Example:

user_input = input('Enter something :')

print(type(user_input))

Output:

Enter something :123 
<class 'str'>

As you can see, we have entered a number as input, but when we print the type of it, it returns as a string. (<class 'str'>).

So, how can we convert the input value into an integer?

Well, to convert the input into an integer we can use the int() function in python.

The int() is used to convert any string, number, or object into a string and then return it.

So, to convert the user input to an integer, we have to wrap the input() function inside the int() function.

Example:

user_input = int(input('Enter number :'))

print(type(user_input))

Output:

Enter number :123
<class 'int'>

In this example, when we enter the number, it gets converted to an integer by int() function and so we get int as the data type of the input value.

Now, let’s see what we get when we enter a string instead of a number in the input prompt.

Enter number :abc
Traceback (most recent call last):
  File "main.py", line 8, in <module>
    user_input = int(input('Enter number :'))
ValueError: invalid literal for int() with base 10: 'abc'

So, when we enter a string, it throws an error in our terminal. And it’s hard for a regular user to understand the error.

So, to solve the error and to give a proper error message to a user, we have to use the try except statement.

Example:

try:
    name = int(input("Enter number: "))
    print('Thanks')
except ValueError:
    print('Please enter a valid number')

So, now if we enter a string instead of a number, we won’t get a long error in our terminal and we can provide a proper error message to the user.

Enter number: abc
Please enter a valid number

And this is how you can handle the error in the python program.

Conclusion: Here, we have learned about how to make input only accept numbers in python, convert the input data into an integer, and handle errors using the try-except statement.

Scroll to Top