What replaced raw_input() in Python 3 and how do you read user input? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

What replaced raw_input() in Python 3 and how do you read user input?

message-square
0

Python 3 renamed Python 2’s raw_input() to input() (and removed Python 2’s unsafe eval-evaluating input() completely), so calling name = input("Enter your name: ") always reads a line from standard input, strips the trailing newline (\n / \r\n), and returns a str directly—which you then explicitly cast with int(...) or float(...) when reading numbers.

Basic Example

# 1. Recommended: Read text input directly as a `str` (identical to Python 2's `raw_input()`)
name = input("Enter your name: ")
print(f"Hello, {name}! Type: {type(name).__name__}")
# Example session:
# Enter your name: Ayesha
# Hello, Ayesha! Type: str

# 2. Reading numeric input in Python 3 requires explicit type conversion:
age = int(input("Enter your age: "))
height = float(input("Enter your height in meters: "))
print(f"Next year you will be {age + 1}, height {height:.2f}m.")

Key Details & Edge Cases

  • Why Python 2’s old input() was removed (eval security risk):
    • In Python 2, input(prompt) was equivalent to eval(raw_input(prompt)), executing arbitrary Python expressions entered by the user (__import__('os').system(...)). Python 3 eliminated that security hazard by promoting raw_input() to input() and removing auto-evaluation. Calling raw_input() in Python 3 raises NameError: name 'raw_input' is not defined.
  • Trailing newlines are stripped automatically (\n and \r\n), while leading/trailing spaces are preserved:
    • input() removes the trailing line break before returning the string, so pressing Enter on an empty prompt returns "" (an empty string). Leading/trailing spaces typed by the user are kept unless you chain .strip() (input("Username: ").strip()).
  • Handling EOFError and KeyboardInterrupt (Ctrl+D / Ctrl+Z / Ctrl+C):
    • If standard input reaches End-of-File (Ctrl+D on macOS/Linux, Ctrl+Z + Enter on Windows, or piped empty stdin), input() raises EOFError. Pressing Ctrl+C raises KeyboardInterrupt. Catch both in interactive CLI tools to exit gracefully without an unhandled traceback.
  • Reading passwords or API tokens without echoing characters (getpass.getpass):
    • input() echoes every typed character to the terminal screen. For secrets, passwords, or PINs, use from getpass import getpass; secret = getpass("Password: ").
  • High-throughput input in competitive programming or multi-line stdin (sys.stdin):
    • input() flushes sys.stdout on every call and incurs prompt-handling overhead. When reading hundreds of thousands of lines from stdin, read via sys.stdin.readline().rstrip("\r\n") or iterate for line in sys.stdin: (or sys.stdin.read().splitlines()).

Comparison of User & Stdin Input Functions in Python 3

Function Return Type Strips Trailing Newline? Echoes Input to Terminal? Best Used When
input(prompt) (Recommended) str Yes (\n / \r\n removed) Yes Interactive CLI prompts and standard user input (replaces Python 2 raw_input()).
int(input(prompt)) / float(input(prompt)) int / float Yes (before conversion) Yes Reading whole numbers or decimals from a prompt (wrap in try ... except ValueError).
getpass.getpass(prompt) str Yes No (hidden input) Prompting for passwords, API keys, or sensitive tokens in a terminal.
sys.stdin.readline() str No (keeps \n; call .rstrip()) N/A (reads stdin stream) High-speed parsing of large piped files or competitive programming inputs.