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 (evalsecurity risk):- In Python 2,
input(prompt)was equivalent toeval(raw_input(prompt)), executing arbitrary Python expressions entered by the user (__import__('os').system(...)). Python 3 eliminated that security hazard by promotingraw_input()toinput()and removing auto-evaluation. Callingraw_input()in Python 3 raisesNameError: name 'raw_input' is not defined.
- In Python 2,
- Trailing newlines are stripped automatically (
\nand\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
EOFErrorandKeyboardInterrupt(Ctrl+D/Ctrl+Z/Ctrl+C):- If standard input reaches End-of-File (
Ctrl+Don macOS/Linux,Ctrl+Z+ Enter on Windows, or piped empty stdin),input()raisesEOFError. PressingCtrl+CraisesKeyboardInterrupt. Catch both in interactive CLI tools to exit gracefully without an unhandled traceback.
- If standard input reaches End-of-File (
- Reading passwords or API tokens without echoing characters (
getpass.getpass):input()echoes every typed character to the terminal screen. For secrets, passwords, or PINs, usefrom getpass import getpass; secret = getpass("Password: ").
- High-throughput input in competitive programming or multi-line stdin (
sys.stdin):input()flushessys.stdouton every call and incurs prompt-handling overhead. When reading hundreds of thousands of lines from stdin, read viasys.stdin.readline().rstrip("\r\n")or iteratefor line in sys.stdin:(orsys.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. |
You must log in or register to comment.
