How to Read Inputs as Numbers in Python
In Python, when you use the input()
function to read user inputs, the values are always stored as strings. This is because the input()
function returns a string.
To perform mathematical operations or comparisons with the user inputs, you need to convert the strings to numbers. In this article, we will explore different ways to read inputs as numbers in Python.
1. Using the int()
function
The int()
function in Python converts a string to an integer. You can use it to convert the user input to numbers.
x = int(input("Enter a number: "))
y = int(input("Enter a number: "))
By using the int()
function, the variables x
and y
will now store the user inputs as integers, allowing you to perform mathematical operations with them.
2. Using the float()
function
If you want to read inputs as decimal numbers, you can use the float()
function to convert the strings to floating-point numbers.
x = float(input("Enter a number: "))
y = float(input("Enter a number: "))
Now, the variables x
and y
will store the user inputs as floating-point numbers, allowing you to perform both integer and floating-point operations with them.
3. Using type casting
You can also use type casting to convert the user inputs to numbers. Type casting is the process of changing the data type of a variable.
x = input("Enter a number: ")
y = input("Enter a number: ")
x = int(x)
y = int(y)
In this approach, the inputs are first stored as strings in the variables x
and y
. Then, using the int()
or float()
function, the strings are converted to numbers.
4. Handling invalid inputs
When reading user inputs as numbers, it is important to handle cases where the user enters invalid input, such as non-numeric characters.
while play:
try:
x = int(input("Enter a number: "))
y = int(input("Enter a number: "))
break
except ValueError:
print("Invalid input. Please enter a number.")
The try-except
block is used to catch any ValueError
that is raised when attempting to convert a non-numeric input to a number. If an invalid input is detected, the error is caught and a message is displayed. The loop continues until valid inputs are provided.
Conclusion
By using the int()
or float()
functions, or by utilizing type casting, you can read user inputs as numbers in Python. It is important to handle invalid inputs to ensure the program does not crash when non-numeric values are entered.
Remember, in Python 2.x, you should use raw_input()
instead of input()
.