How do I use raw_input in Python 3?
In Python 2, raw_input()
was the function used to accept user input from the command line, returning it as a string. However, Python 3 removes raw_input()
in favor of a single input()
function that behaves much like raw_input()
did in Python 2.
1. Direct Replacement
- If your Python 2 code has
raw_input()
, simply replace it withinput()
when migrating to Python 3. - In Python 3,
input()
returns user input as a string without evaluating it (just likeraw_input()
did in Python 2).
2. Example of Using input()
in Python 3
user_input = input("Enter your name: ") print(f"Hello, {user_input}!")
- This code prompts the user to enter their name and then prints a greeting.
3. Why Did Python 3 Remove raw_input()
?
- In Python 2,
raw_input()
returned a string, whileinput()
tried to evaluate the user input as Python code—which could be both confusing and insecure in many cases. - Python 3 simplifies things by making
input()
always return a string, combining both functionalities into a single, safer function.
4. Compatibility Tips
If you’re maintaining a codebase that needs to run in both Python 2 and 3, you can handle the renaming with a small compatibility block:
try: input = raw_input except NameError: pass
This snippet rebinds input
to raw_input
in Python 2, while leaving Python 3 behavior unchanged.
5. Further Learning
If you want to improve your Python skills beyond basic I/O operations, consider these courses from DesignGurus.io:
- Grokking Python Fundamentals: Ideal for beginners who want a solid grounding in Python’s core features and best practices.
- Grokking the Coding Interview: Patterns for Coding Questions: Perfect if you’re preparing for coding interviews; learn problem-solving patterns and how to effectively use Python.
Key Takeaway
There is no raw_input()
in Python 3. Use input()
instead.
TAGS
Python
CONTRIBUTOR
TechGrind