Python 3
raw_input
input function
Python programming
user input

How do I use raw_input in Python 3?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

raw_input() does not exist in Python 3 — it was renamed to input(). In Python 2, raw_input() returned user input as a string, while input() evaluated the input as a Python expression (equivalent to eval(raw_input())). Python 3 removed this dangerous eval behavior and made input() behave like Python 2's raw_input(), always returning a string. If you are porting Python 2 code to Python 3, replace every raw_input() call with input(). For code that needs to run on both versions, use a compatibility shim.

Python 2 vs Python 3 Comparison

python
1# Python 2
2name = raw_input("Enter your name: ")   # Returns string
3age = input("Enter your age: ")          # DANGEROUS: evaluates as Python code!
4# If user types "42", age is the integer 42
5# If user types "__import__('os').system('rm -rf /')", it executes!
6
7# Python 3
8name = input("Enter your name: ")       # Returns string (safe)
9# raw_input("Enter your name: ")        # NameError: name 'raw_input' is not defined

Python 3's input() is always safe — it returns whatever the user types as a string, without evaluation.

Basic Usage of input() in Python 3

python
1# Simple string input
2name = input("What is your name? ")
3print(f"Hello, {name}!")
4
5# Input always returns a string
6age_str = input("How old are you? ")
7print(type(age_str))  # <class 'str'>
8
9# Convert to other types manually
10age = int(input("How old are you? "))
11height = float(input("Height in meters: "))
python
1# No prompt argument — blank prompt
2data = input()  # Waits for input with no message displayed
3
4# Multi-word input
5sentence = input("Enter a sentence: ")
6words = sentence.split()
7print(f"You entered {len(words)} words")

Type Conversion Patterns

python
1# Integer input with error handling
2while True:
3    try:
4        age = int(input("Enter your age: "))
5        break
6    except ValueError:
7        print("Please enter a valid number")
8
9# Float input
10price = float(input("Enter price: "))
11
12# Boolean input
13answer = input("Continue? (yes/no): ").lower().strip()
14if answer in ("yes", "y"):
15    print("Continuing...")
16
17# List of integers
18numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
19print(numbers)  # e.g., [1, 2, 3, 4, 5]
20
21# Multiple values on one line
22x, y = input("Enter x y: ").split()
23x, y = int(x), int(y)
24
25# Or more concisely
26x, y = map(int, input("Enter x y: ").split())

Writing Code Compatible with Python 2 and 3

python
1# Method 1: try/except
2try:
3    input = raw_input  # Python 2: use raw_input as input
4except NameError:
5    pass               # Python 3: input already exists
6
7name = input("Enter name: ")  # Works in both versions
8
9# Method 2: six library
10from six.moves import input
11name = input("Enter name: ")  # Works in both versions
12
13# Method 3: sys.version check
14import sys
15if sys.version_info[0] >= 3:
16    get_input = input
17else:
18    get_input = raw_input
19
20name = get_input("Enter name: ")

Reading Multiple Lines of Input

python
1# Read until empty line
2lines = []
3print("Enter text (empty line to stop):")
4while True:
5    line = input()
6    if line == "":
7        break
8    lines.append(line)
9text = "\n".join(lines)
10
11# Read a fixed number of lines
12n = int(input("How many lines? "))
13lines = [input() for _ in range(n)]
14
15# Read from stdin (for competitive programming / piped input)
16import sys
17for line in sys.stdin:
18    print(line.strip())

Input with Default Values

python
1def input_with_default(prompt, default):
2    """Input function that accepts a default value."""
3    result = input(f"{prompt} [{default}]: ").strip()
4    return result if result else default
5
6name = input_with_default("Username", "admin")
7port = int(input_with_default("Port", "8080"))
8
9# Using walrus operator (Python 3.8+)
10name = val if (val := input("Name [admin]: ").strip()) else "admin"

Secure Input (Passwords)

python
1import getpass
2
3# getpass hides the typed characters
4password = getpass.getpass("Enter password: ")
5# User types but nothing is displayed on screen
6
7# Confirm password pattern
8password = getpass.getpass("Password: ")
9confirm = getpass.getpass("Confirm: ")
10if password != confirm:
11    print("Passwords do not match!")

getpass.getpass() works like input() but suppresses the echo, making it suitable for password entry.

Common Pitfalls

  • Using raw_input() in Python 3: This raises NameError: name 'raw_input' is not defined. Replace all raw_input() calls with input(). Use find-and-replace or the 2to3 tool for automated migration.
  • Forgetting that input() always returns a string: input("Age: ") returns "25" (a string), not 25 (an integer). Arithmetic like input() + 1 raises TypeError. Always cast explicitly with int(), float(), etc.
  • Using Python 2's input() for user data: Python 2's input() calls eval() on the result, which executes arbitrary code. If porting from Python 2, replace input() with raw_input() first, then rename to input() for Python 3. Never use eval(input()) in production code.
  • Not handling ValueError on type conversion: int(input()) crashes if the user types non-numeric text. Always wrap conversions in try/except ValueError or validate the input string before converting.
  • input() blocking in scripts that read from pipes: When stdin is redirected (e.g., echo "data" | python script.py), input() reads from the pipe, not the terminal. Use sys.stdin.isatty() to detect whether input is interactive, and sys.stdin for line-by-line processing of piped data.

Summary

  • Python 3 renamed raw_input() to input() — both return a string
  • Python 2's input() (which eval'd the result) was removed for security
  • Always convert input() results explicitly: int(input()), float(input())
  • Use try/except ValueError for safe type conversion of user input
  • For Python 2/3 compatibility, use try: input = raw_input or the six library
  • Use getpass.getpass() for password input that hides typed characters

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.