How To Read Python Input As Number
Python's input()
function reads any input as a string by default. Therefore you need to manually convert it to the actual data type you'd like to use. Here is how to read input as an integer:
number = int(input("Enter a number:"))
print(number)
Pretty simple, right? All we did is to wrap the usual input()
function in the int()
constructor. Running this command will prompt us with the message "Enter a number:". After the user inputs a number, input()
will read it as a string, and the int()
will convert that string to a base-10 integer. In the end, we'll have the integer value of the input stored in the number
variable:
>>> number = int(input("Enter a number:"))
Enter a number:6
>>> print(number)
6
Alternatively, you can also read different base numbers by passing one additional argument into the int()
constructor:
number = int(input("Enter a number:"), 2)
This will read a base-2 value from the input, convert it to the base-10 number and assign that value to the number
variable.
Additionally, you can read float numbers in the same manner as previously shown:
number = float(input("Enter a number:"))
Advice: For more in-depth overview of how to get the user input in Python, read our "Getting User Input in Python" article.