How can we read inputs as integers in Python?

PythonServer Side ProgrammingProgramming

Python 3.x has an in-built input() function to accept user input. This input() function returns a string data and it can be stored in string variable.


It must be converted to integer using built-in function int()

>>> var=int(input("enter age"))
enter age21
>>> var
>>> type(var)
 <class 'int'>

Here, if user input contains digits only, int() function parses integer otherwise a ValueError is encountered.

In Python 2.x, input() function evaluates the input and accordingly appropriate data type is returned.

Updated on 13-Dec-2019 11:18:27