Convert Input to Number in Python
In Python 3.x, the input() function parse user input as a string even if it contains only digits.
>>> import sys >>> data=input("Enter a Value: ") Enter a Value: 100 >>> data '100' >>> type(data) <class 'str'> >>> data=input("Enter a Value: ") Enter a Value: Hello >>> data 'Hello' >>> type(data) <class 'str'>
How do we ensure a numeric input from the user? Most common alternative is to parse return value of the input()
function to integer with int() function
>>> data=int(input("Enter a Number: ")) Enter a Number: 100 >>> data 100 >>> type(data) <class 'int'>
However, this is prone to error. If the user inputs non-numeric data, ValueError
is raised.
>>> data=int(input("Enter a Number: ")) Enter a Number: hello Traceback (most recent call last): File "<pyshell#34>", line 1, in <module> data=int(input("Enter a Number: ")) ValueError: invalid literal for int() with base 10: 'hello'
This can be taken care of by Python's exception handling technique. The following code keeps on asking for user input till an integer number is given.
while True: try: data=int(input("Enter a Number: ")) print ("You entered: ", data) break; except ValueError: print ("Invalid input")
Enter a Number: hello Invalid input Enter a Number: abcd Invalid input Enter a Number: 100 You entered: 100
You can use the built-in float() function if a floating-point number is expected to be input.
Another method is to use the eval() function. Apart from other applications of this built-in function, it is a convenient tool to check if the input is a valid number. In case it is not, the Python interpreter raises NameError
while True: try: data=eval(input("Enter a Number: ")) print ("You entered: ",data) break; except NameError: print ("Invalid input")
Enter a Number: hello Invalid input Enter a Number: abcd Invalid input Enter a Number: 12.34 You entered: 12.34
Convert Input to Number in Python 2.x
Python 2.x has two built-in functions for accepting user input. the raw_input()
and input()
. The input()
function is intelligent as it judges the data type of data read, whereas the raw_input()
always treats the input as a string. So, always use the input()
function in Python 2.x.
>>> data=input("enter something : ") enter something : 100 >>> data 100 >>> type(data) <type 'int'> >>> data=input("enter something : ") enter something : Hello' >>> data 'Hello' >>> type(data) <type 'str'>