Getting User Input in Python
In many programs, you’ll need to interact with the user, asking for information and then using that information to perform tasks. Python provides built-in functions to handle this interaction, primarily raw_input()
in Python 2 and input()
in Python 3. This tutorial explains how to use these functions effectively.
Understanding the Basics
The core functionality is simple: these functions allow your program to pause execution and wait for the user to type something and press Enter. The input the user provides is then stored as a string within your program.
Python 2: Using raw_input()
In Python 2, the raw_input()
function is the standard way to get text input from the user.
name = raw_input("What is your name? ")
print "Hello, " + name + "!"
In this example:
raw_input("What is your name? ")
displays the prompt "What is your name? " to the user and waits for them to type something.- Whatever the user types (before pressing Enter) is captured as a string and assigned to the variable
name
. print "Hello, " + name + "!"
then prints a greeting using the user’s input.
Important: raw_input()
always returns a string, even if the user types a number. If you need to treat the input as a number (integer or float), you’ll need to explicitly convert it:
age_str = raw_input("How old are you? ")
age = int(age_str) # Convert the string to an integer
print "You will be " + str(age + 1) + " next year."
Python 3: Using input()
In Python 3, the raw_input()
function has been removed. The input()
function now performs the same function as raw_input()
in Python 2: it reads a line from input and returns it as a string.
name = input("What is your name? ")
print("Hello, " + name + "!")
age_str = input("How old are you? ")
age = int(age_str)
print("You will be " + str(age + 1) + " next year.")
This code is identical in behavior to the Python 2 example, but uses the input()
function instead of raw_input()
.
Handling Different Input Types
As mentioned earlier, input()
(in Python 3) and raw_input()
(in Python 2) always return strings. Here’s how to handle other data types:
-
Integers:
number_str = input("Enter a number: ") number = int(number_str) print(number * 2)
-
Floats:
price_str = input("Enter the price: ") price = float(price_str) print(price * 1.10) # Calculate price with 10% tax
-
Booleans: You’ll need to parse strings like "True" or "False" to get a boolean value:
answer = input("Do you agree? (True/False) ") is_agree = answer.lower() == "true" print(is_agree)
Error Handling
When converting user input to a specific data type, it’s important to handle potential errors. For example, if the user enters text when you expect a number, the int()
or float()
function will raise a ValueError
. You can use try-except
blocks to gracefully handle these errors:
try:
age_str = input("How old are you? ")
age = int(age_str)
print("You are", age, "years old.")
except ValueError:
print("Invalid input. Please enter a number.")
This code will attempt to convert the input to an integer. If the conversion fails, it will catch the ValueError
and print an error message. This prevents your program from crashing and provides a more user-friendly experience.
Best Practices
- Always validate user input: Check if the input is in the expected format and within a reasonable range.
- Provide clear prompts: Tell the user exactly what you expect them to enter.
- Handle potential errors gracefully: Use
try-except
blocks to prevent crashes and provide informative error messages. - Convert input to the correct data type: Don’t assume the input is already in the format you need.
- Consider using libraries for more complex input validation: Libraries like
regex
can help you validate input based on specific patterns.