How can I read inputs as numbers?
Categories:
Reading User Input as Numbers in Python

Learn how to correctly read user input and convert it into integer or float numbers in Python 2.7 and Python 3.x, handling potential errors gracefully.
When developing interactive Python applications, you often need to obtain numerical input from the user. However, Python's built-in input functions (input()
in Python 3.x and raw_input()
in Python 2.7) always return strings. Attempting to perform mathematical operations directly on these string inputs will result in errors. This article will guide you through the correct methods to convert string inputs into numerical types (integers and floats) and best practices for handling invalid input.
Understanding Python's Input Functions
The primary challenge when reading numbers in Python stems from how input functions operate. They are designed to capture raw text from the user, which is always treated as a string. To use this text as a number, an explicit conversion step is required. This conversion is crucial for any arithmetic operations or comparisons that rely on numerical values.
flowchart TD A[Start] --> B["User enters input"]; B --> C{"Python's input() / raw_input()"}; C --> D["Returns string value"]; D --> E{"Is conversion needed?"}; E -- Yes --> F["Convert to int() or float()"]; E -- No --> G["Process as string"]; F --> H["Use numerical value"]; G --> I["Use string value"]; H --> J[End]; I --> J[End];
Flowchart illustrating the process of reading user input and the necessity of type conversion.
Converting Input to Integers
To convert a string input into an integer, you use the int()
constructor. This function attempts to parse the string and return its integer representation. If the string does not represent a valid integer, int()
will raise a ValueError
. It's essential to anticipate this and implement error handling to create robust applications.
Python 3.x
Python 3.x
while True: try: user_input = input("Enter an integer: ") number = int(user_input) print(f"You entered the integer: {number}") break # Exit loop if conversion is successful except ValueError: print("Invalid input. Please enter a whole number.")
Python 2.7
Python 2.7
while True: try: user_input = raw_input("Enter an integer: ") number = int(user_input) print "You entered the integer: %d" % number break # Exit loop if conversion is successful except ValueError: print "Invalid input. Please enter a whole number."
int()
or float()
conversion calls in a try-except
block to gracefully handle ValueError
exceptions. This prevents your program from crashing if the user enters non-numeric text.Converting Input to Floating-Point Numbers
For numbers that may contain decimal points, you'll need to convert the input string to a floating-point number using the float()
constructor. Similar to int()
, float()
will raise a ValueError
if the input string cannot be interpreted as a valid floating-point number. The error handling strategy remains the same.
Python 3.x
Python 3.x
while True: try: user_input = input("Enter a decimal number: ") number = float(user_input) print(f"You entered the float: {number}") break # Exit loop if conversion is successful except ValueError: print("Invalid input. Please enter a valid decimal number.")
Python 2.7
Python 2.7
while True: try: user_input = raw_input("Enter a decimal number: ") number = float(user_input) print "You entered the float: %f" % number break # Exit loop if conversion is successful except ValueError: print "Invalid input. Please enter a valid decimal number."
input()
function in Python 2.7 behaves differently than in Python 3.x. In Python 2.7, input()
attempts to evaluate the input as a Python expression, which can be a security risk. Always use raw_input()
for string input in Python 2.7, then convert it.Practical Steps for Robust Number Input
To ensure your program reliably gets numerical input, follow these steps. This approach combines input, conversion, and error handling into a reusable pattern.
1. Prompt for Input
Use input()
(Python 3.x) or raw_input()
(Python 2.7) to display a clear message to the user, indicating what kind of input is expected.
2. Attempt Conversion
Place the conversion function (int()
or float()
) inside a try
block. This is where the actual string-to-number conversion happens.
3. Handle Errors
If the conversion fails (e.g., user types 'hello' instead of '5'), a ValueError
will be raised. Catch this exception in an except ValueError
block and inform the user about the invalid input.
4. Loop Until Valid
Encapsulate the input and conversion logic within a while True
loop. Use a break
statement to exit the loop only when valid input has been successfully converted, prompting the user again if input is invalid.