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.

Published on 27-Dec-2017 00:09:26