raw_input in Python: The Complete Guide + Python 3 Equivalent (With Examples)

If you’ve ever run a Python script and hit this error:

NameError: name 'raw_input' is not defined

— You’re in the right place. That error means you’re using Python 3, and raw_input was removed in Python 3. Don’t worry, though. The fix is simple, and I’ll walk you through everything you need to know in this guide.

Let’s get into it.

What is raw_input in Python?

raw_input() was a built-in function in Python 2 that let you collect input from the user via the keyboard. When you called it, your program would pause, wait for the user to type something and press Enter, and then return whatever they typed as a string.

Here’s the basic syntax:

# Python 2 only
variable = raw_input(prompt)
  • prompt — the message shown to the user before they type
  • The function always returns the input as a string, no matter what the user types

A simple example in Python 2:

# Python 2
name = raw_input("Enter your name: ")
print("Hello, " + name + "!")

Output:

Enter your name: Emily
Hello, Emily!

Important: If you are on Python 3, skip to the next section. raw_input does not exist in Python 3 and will throw a NameError if you try to use it.

Why was raw_input removed in Python 3?

In Python 2, there were actually two input functions:

  1. raw_input() — always returned the input as a string (safe)
  2. input() — tried to evaluate whatever the user typed as a Python expression (dangerous)

The Python 2 input() was a real security problem. If someone typed __import__(‘os’).system(‘rm -rf /’) into a prompt, Python 2 would actually try to run it. That’s not something you want in any real application.

When Python 3 came out, the developers made a clear decision: remove the dangerous input() entirely, rename raw_input() to input(), and keep the safe, string-returning behavior. So in Python 3:

  • raw_input() → removed
  • input() → now does what raw_input() used to do

That’s it. The behavior you want from raw_input in Python 2 is exactly what input() gives you in Python 3.

raw_input vs input — Python 2 vs Python 3

Here’s a clear side-by-side so you can see exactly how these functions differ across versions:

Python 2 raw_input()Python 2 input()Python 3 input()
ReturnsAlways a stringEvaluates as expressionAlways a string
Security riskNoneYes — can execute codeNone
Still available?❌ Removed in Python 3❌ Removed in Python 3✅ Yes, use this
Python 3 equivalentinput()eval(input())
Needs type conversion?Yes, manuallyNo (auto-detected)Yes, manually

The takeaway: if you’re on Python 3, use input() and you’ll get the same behavior that raw_input() gave you in Python 2.

How to Use input() in Python 3 (The raw_input Replacement)

Here’s the syntax for Python 3’s input():

variable = input(prompt)

According to the official Python documentation, if a prompt argument is provided, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping the trailing newline), and returns it.

A basic example:

# Python 3
name = input("Enter your name: ")
print("Hello, " + name + "!")

Output:

Enter your name: Jake
Hello, Jake!

I executed the above example code and added the screenshot below.

raw_input in Python

One thing to note: input() always returns a string, even if the user types a number. So if someone types 25, Python stores it as the string “25”, not the integer 25. I’ll show you how to handle type conversion in the next section.

How to Convert input() to Integer, Float, or List

This is one of the most common things you’ll do with input(), and a section that trips up a lot of beginners. Since everything comes back as a string, you need to convert it to the type you want explicitly.

Integer Input

age = int(input("Enter your age: "))
print(f"You are {age} years old.")

Output:

Enter your age: 29
You are 29 years old.

Float Input

price = float(input("Enter the product price: $"))
tax = price * 0.08
print(f"Tax amount: ${tax:.2f}")

Output:

Enter the product price: $49.99
Tax amount: $4.00

List Input from Comma-Separated Values

items = input("Enter your grocery items (comma-separated): ").split(",")
items = [item.strip() for item in items]
print("Your list:", items)

Output:

Enter your grocery items (comma-separated): apples, milk, bread, eggs
Your list: ['apples', 'milk', 'bread', 'eggs']

I executed the above example code and added the screenshot below.

raw_input Python

The .strip() call removes any extra spaces the user might type around the commas — a small touch that makes your program much more forgiving.

Real-World Example — Customer Data Entry Script

Let’s put input() to work in something practical. Here’s a simple customer data collection script that stores entries in a list and lets the user type done to stop:

# Python 3 — customer data entry
print("=== Customer Entry Form ===")
print("Type 'done' when you're finished.\n")

customers = []

while True:
name = input("Customer name: ").strip()
if name.lower() == "done":
break
if not name:
print("Name can't be empty. Try again.\n")
continue

email = input("Customer email: ").strip()
state = input("State (e.g. CA, TX, NY): ").strip().upper()

customers.append({"name": name, "email": email, "state": state})
print(f"✅ Added: {name} ({email}) from {state}\n")

print(f"\nTotal customers added: {len(customers)}")
for c in customers:
print(f" - {c['name']} | {c['email']} | {c['state']}")

Sample Output:

=== Customer Entry Form ===
Type 'done' when you're finished.

Customer name: Sarah Johnson
Customer email: sarah@email.com
State (e.g. CA, TX, NY): ca
✅ Added: Sarah Johnson (sarah@email.com) from CA

Customer name: done

Total customers added: 1
- Sarah Johnson | sarah@email.com | CA

A few things worth pointing out in this example:

  • I used .strip() to remove accidental leading/trailing spaces from every input
  • The .lower() check makes the quit command case-insensitive, so “Done”, “DONE”, and “done” all work
  • The .upper() on the state makes formatting consistent automatically
  • I check for empty names before adding them to the list

How to Validate User Input in Python

User input is unpredictable. People will type letters when you expect numbers, leave fields blank, or enter values out of the expected range. Here’s how to handle the most common scenarios.

Validate an Integer with a Range Check

while True:
try:
age = int(input("Enter your age (1-120): "))
if 1 <= age <= 120:
break
else:
print("Please enter an age between 1 and 120.")
except ValueError:
print("That's not a valid number. Please try again.")

print(f"Got it! You are {age} years old.")

Sample Output:

Enter your age (1-120): abc
That's not a valid number. Please try again.
Enter your age (1-120): 200
Please enter an age between 1 and 120.
Enter your age (1-120): 34
Got it! You are 34 years old.

I executed the above example code and added the screenshot below.

Python raw_input

Validate a Yes/No Response

while True:
answer = input("Do you want to continue? (yes/no): ").strip().lower()
if answer in ("yes", "no"):
break
print("Please type 'yes' or 'no'.")

if answer == "yes":
print("Great, continuing...")
else:
print("Okay, exiting.")

Validate a Choice from a Menu

options = {"1": "Check balance", "2": "Transfer funds", "3": "Exit"}

print("--- Banking Menu ---")
for key, val in options.items():
print(f" {key}. {val}")

while True:
choice = input("\nEnter your choice (1-3): ").strip()
if choice in options:
print(f"You selected: {options[choice]}")
break
print("Invalid choice. Please enter 1, 2, or 3.")

The pattern across all three examples is the same: loop until you get valid input, and handle errors with try/except when type conversion is involved. This is standard practice in Python.

Common Errors with raw_input and How to Fix Them

Here are the three errors you’ll run into most often, and exactly what to do about each one:

ErrorCauseFix
NameError: name ‘raw_input’ is not definedYou’re on Python 3Replace raw_input() with input()
ValueError: invalid literal for int() with base 10User typed text when you expected a numberWrap int(input(…)) in a try/except ValueError block
Empty input accepted silentlyNo check for blank inputAdd if not user_input.strip(): continue
Empty input is accepted silentlyInput stream ended unexpectedly (common in testing/scripts)Wrap input() in a try/except EOFError

Let’s look at the ValueError fix in practice:

# Without error handling — crashes if user types letters
score = int(input("Enter your test score: ")) # ❌ Risky

# With error handling — handles bad input gracefully
while True:
try:
score = int(input("Enter your test score: "))
break
except ValueError:
print("Please enter a number only.") # ✅ Safe

Python 2 and Python 3 Compatibility Shim

If you’re working on a legacy codebase that has to run on both Python 2 and Python 3, here’s a clean compatibility shim I use. It handles the raw_input / input difference in one shot:

# Works seamlessly in both Python 2 and Python 3
try:
input = raw_input # In Python 2, make input() behave like raw_input()
except NameError:
pass # In Python 3, raw_input doesn't exist — input() is already correct

# Now use input() everywhere
name = input("Enter your name: ")
city = input("Enter your city: ")
print(f"Hello {name} from {city}!")

What’s happening here:

  • In Python 2, raw_input exists, so we reassign input = raw_input to override the unsafe built-in
  • In Python 3, raw_input doesn’t exist at all, so the except NameError block runs, and we just skip it — input() already works correctly

This is the cleanest approach for cross-version compatibility without using six or future libraries.

Advanced: Use sys.stdin as an Alternative to input()

For most interactive scripts, input() is all you need. But there are situations where you’ll want to use sys.stdin instead:

  • Reading input that’s being piped in from another program or file
  • Competitive programming problems that send input via stdin
  • Automated testing and CI/CD scripts where there’s no keyboard

Here’s how to use it:

import sys

# Read a single line from stdin
line = sys.stdin.readline().strip()
print("You entered:", line)

Reading multiple lines until there’s no more input (useful in piping scenarios):

import sys

print("Reading all lines from stdin:")
for line in sys.stdin:
print("Line:", line.strip())

Running this from the command line with piped input:

echo "Hello from the terminal" | python3 script.py

Output:

Reading all lines from stdin:
Line: Hello from the terminal

You can also read a file’s content as input:

python3 script.py < data.txt

This is particularly useful when writing scripts that other programs need to interact with, or when you’re building tools that need to process batch data without manual keyboard input.

Quick Decision Guide — Which Input Method Should You Use?

SituationUse This
Interactive Python 3 scriptinput()
Old Python 2 scriptraw_input()
Codebase supporting both Python 2 and 3Compatibility shim (try/except) above
Piped input from another program or filesys.stdin
Structured command-line argumentsargparse module
GUI applicationtkinter.Entry widget

FAQs

Is raw_input available in Python 3?

No. raw_input() was removed in Python 3. Use input() instead — it behaves exactly the same way as Python 2’s raw_input().

Does input() in Python 3 evaluate expressions like input() did in Python 2?

No. Python 3’s input() always returns a plain string. It does not evaluate expressions. If you need to evaluate an expression from user input (which is rare and should be done carefully), use eval(input()).

Q: How do I take multiple inputs on one line in Python?

Use .split():
first, last = input(“Enter your first and last name: “).split() print(f”First: {first}, Last: {last}”)
Enter your first and last name: Michael Carter
First: Michael, Last: Carter

What happens if the user just presses Enter without typing anything?

input() returns an empty string "". Always check for this in your validation logic with if not user_input.strip().

Why does input() always return a string even if I type a number?

That’s by design. Python doesn’t assume what type you want — you convert explicitly. Use int(), float(), or other type functions to convert as needed.

You may also read:

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.