How to Use the raw_input Function in Python for User Input?

The raw_input function is used to prompt users for text input and store that input as a string variable in your Python programs. In this tutorial, I will explain how to use the raw_input function in Python to get user input from the command line.

What is the raw_input Function in Python?

The raw_input function is a built-in Python function that prompts the user to type in some text at the command line and returns that text as a string. It allows your program to pause and wait for the user to enter input before continuing execution.

Here’s the basic syntax of the raw_input function:

user_input = raw_input("Enter some text: ")

When this line of code is executed, it will display the prompt message “Enter some text: ” in the console and wait for the user to type something and press Enter. Whatever text the user types will be returned as a string and stored in the user_input variable.

One key thing to note is that raw_input explicitly converts the entered data into a string, regardless of what the user types in. So even if the user enters a number like “42”, it will be stored as the string “42” rather than the integer value 42.

Check out How to Iterate Through Tuples in Python?

raw_input in Python Example

To understand how raw_input can be used to solve real programming problems, let’s walk through an example. Imagine you are building a simple command-line application to help a small business in the USA manage their customer data. One feature you want to add is the ability to input a new customer’s name and email address.

Here’s how you could use raw_input to implement this:

print("Enter a new customer (type 'quit' to exit)")

while True:
    name = raw_input("Customer name: ")
    if name == 'quit':
        break

    email = raw_input("Customer email: ")

    print("New customer added:")
    print("Name: " + name) 
    print("Email: " + email)
    print("")

In this code:

  1. We start with a print statement to explain to the user how to exit the input loop by typing ‘quit’.
  2. We enter a while loop that will keep prompting for new customers until the user types ‘quit’ for the name.
  3. Inside the loop, we use raw_input to prompt for the customer name and email, storing them as variables.
  4. After getting a new name and email, we print out a confirmation message displaying the entered data.
  5. The loop continues, prompting for additional customers until ‘quit’ is entered for the name.

Here’s an example of what the user would see when running this code:

Enter a new customer (type 'quit' to exit)
Customer name: John Smith
Customer email: [email protected]
New customer added:
Name: John Smith
Email: [email protected]

Customer name: quit

As you can see, the raw_input function made it easy to prompt the user for each piece of data we needed and store their responses as strings for later use.

Read How to Calculate the Dot Product in Python Without NumPy?

Validate User Input with raw_input in Python

One potential issue with reading user input is validating that the entered text meets your program’s expectations. Since raw_input always returns a string, you may need to do some additional parsing and error checking depending on what type of data you are expecting.

For example, let’s say we wanted to extend our customer input example to also prompt for the customer’s age. We would expect the user to enter a valid integer value. Here’s one way we could handle that:

while True:
    age_str = raw_input("Customer age: ")

    try:
        age = int(age_str)
    except ValueError:
        print("Invalid age, please enter a number.")
        continue

    if age < 0:
        print("Invalid age, please enter a positive number.")
        continue
    else:
        break

print("Customer age:", age)

The key steps here are:

  1. We prompt the user for their age using raw_input, storing the result in a string variable age_str.
  2. We use a try/except block to attempt converting age_str to an integer using int(). If this fails due to age_str not being a valid number, a ValueError is raised.
  3. If a ValueError occurs, we catch it, print an error message, and use continue to go back to the start of the loop and prompt again.
  4. If the integer conversion succeeds, we next check if the age value is negative. If so, we again print an error and continue the loop.
  5. If we make it past the error checks, we know age is a valid non-negative integer, so we break out of the loop and continue with our program.

By adding validation logic around our raw_input prompts, we can ensure that our program only proceeds if the user provides the expected type of input. This makes our code more robust and user-friendly.

Conclusion

The raw_input function is used to get text input from users in Python programs. Whether you are building a command-line utility, a text-based game, or any other type of interactive Python application, raw_input provides a convenient way to prompt users for data and incorporate their responses into your program’s flow. In this tutorial, I explained how to use the raw_input function in Python for user input.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.