In this tutorial, we will learn how to read user 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 are
raw_input reads the user input as a raw string and its return value is simply
input gets the user input and then evaluates the string and the result of the evaluation is returned.
>>> 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'>)
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(*.*)
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