Why do I get NameError name '...' is not defined or a SyntaxError, or a number instead of a string when using the input function in Python 2.x?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In Python 2, input() evaluates what the user types as Python code, while raw_input() returns a plain string. This historical behavior causes confusing errors like NameError and SyntaxError when users type normal text. It can also return numeric values instead of strings when users type numbers. The safest fix in Python 2 code is to use raw_input(), or better, migrate to Python 3 where input() always returns strings.
Core Sections
1. Python 2 behavior difference
Typing john at input() raises NameError because Python treats it as variable name.
2. Why numbers behave differently
If user types 123, input() evaluates it as integer literal and returns int, not string.
This inconsistency causes downstream bugs.
3. Safe pattern in Python 2
Explicit parsing is predictable and secure.
4. Python 3 migration
In Python 3:
This always returns str, matching most user expectations.
5. Security implications
Python 2 input() executing arbitrary expressions is dangerous for untrusted input. Treat it as unsafe in scripts receiving user data.
6. Compatibility helper
For dual-version code:
This unifies behavior across versions.
Common Pitfalls
- Using Python 2
input()expecting plain text string behavior. - Relying on implicit type results from user-entered expressions.
- Treating Python 2 and Python 3
input()as equivalent APIs. - Exposing
input()evaluation behavior to untrusted users. - Mixing migration code without clear version guards.
Summary
The confusion comes from Python 2 design: input() evaluates expressions, raw_input() returns strings. Use raw_input() in Python 2 or migrate to Python 3 input() for safe, predictable input handling. Explicit parsing and version-aware code eliminate these runtime surprises.

