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.

Example

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

>>> var=int(input("enter age"))
enter age21
>>> var
21
>>> 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.

raja
Published on 26-Dec-2017 19:39:26
Advertisements