python read number as input

How to Read Inputs as Numbers in Python

Python allows you to read inputs in your python scripts. Before python 3, the python interpreter used to interpret number inputs as int or float, and string inputs as strings. But since python 3, all user inputs are read as strings. This is because in python 2+, the interpreter used to evaluate user input such as expressions, which posed several security risks. But sometimes, you may need to read inputs as numbers in Python. In this article, we will learn how to do this.


How to Read Inputs as Numbers in Python

As you might have expected, since python 3+ reads all inputs as strings, you need to read the input first and then typecast it into the desired data type.

Here is an example to read integer input.

>>> x = int(input("Enter a number: "))
>>> Enter a number: 71
>>> x
 71

In this case, we accept the user input using input() function and then call int() function on the user input string to convert it into integer.

Here is an example to read float input.

>>> x = float(input("Enter a number: "))
>>> Enter a number: 71.4
>>> x
 71.4

In python 3, if you enter an expression as user input, it will not be evaluated but stored as string.

>>> x = input("Enter a number: ")
>>> Enter a number: 7+1
>>> x
 '7+1'

If you are using python 2.x, you can directly use input function without typecasting, to read numbers.

>>> x = input("Enter a number: ")
>>> Enter a number: 71
>>> x
 71

Here is another example to accept the sum of two numbers as input in python 2.x.

>>> x = input("Enter a number: ")
>>> Enter a number: 7+1
>>> x
 8

In python, if you want to accept a number but don’t want it to be evaluated, then use raw_input() function.

>>> x = raw_input("Enter a number: ")
>>> Enter a number: 71
>>> x
 71


Accept Multiple Inputs

Above examples only accept single inputs. If you want to accept multiple inputs you will have to add separate statements.

>>> x = int(input("Enter a number: "))
>>> Enter a number: 71
>>> y = int(input("Enter a number: "))
>>> Enter a number: 81
>>> x
 71
>>> y
 81

Sometimes you may want to accept multiple inputs in a single line. For such cases, use map() function. Here is an example to accept multiple inputs and store them as array.

>>> arr = map(int, raw_input().split())
>>> 1 2 3
>>> arr
 [1,2,3]

Here is an example to accept two integers on a single line.

>>> num1, num2 = map(int, raw_input().split())
>>> 1 2
>>> num1
 1
>>> num2
 2

In this article, we have learnt several ways to read number input in Python. You can use these commands as per your requirement.

Also read:

How to Split List into Evenly Sized Chunks in Python
How to Fix Temporary Failure in Name Resolution in Linux
How to Add Route in Linux
How to Change Root Password in CentOS, RHEL, Fedora
How to Ping Specific Port in Linux

Leave a Reply

Your email address will not be published. Required fields are marked *