How to read input as integers in Python

Read user input as integers in Python 2.x

Python 2.7 has two functions to read the user input, that is raw_input and input.

raw_input reads the user input as a raw string and its return value is simply string.

input gets the user input and then evaluates the string and the result of the evaluation is returned.

For example,

>>> number = raw_input("Enter a number: ")
Enter a number: 1 + 1
>>> number, type(number)
('1 + 1', <type 'str'>)

>>> number = input("Enter a number: ")
Enter a number: 1 + 1
>>> number, type(number)
(2, <type 'int'>)
Warning

Consider twice when you use input in Python 2.x. It could impose security issues because input evaluates whatever user types.

Let’s say if you have already imported os in your program and then it asks for user input,

>>> number = input("Enter a number: ")
Enter a number: os.remove(*.*)

Your input os.remove(*.*) is evaluated and it deletes all the files in your working dictionary without any notice!

Read user input as integers in Python 3.x

raw_input is obsolete in Python 3.x and it is replaced with input in Python 3.x. It only gets the user input string but doesn’t evaluate the string because of the security risk as described above.

Therefore, you have to explicitly convert the user input from the string to integers.

>>> number = int(input("Enter a number: "))
Enter a number: 123
>>> number
123