Introduction to Python
Python 2 vs Python 3
Key differences and migration
Interview: Understanding legacy code
Python 3 is the present and future of the language. Python 2 reached End of Life (EOL) on January 1, 2020. However, understanding the differences is still important for maintaining legacy codebases and answering interview questions.
Major Differences
Print Statement vs Function
Python 2 uses print as a statement, while Python 3 makes it a function with more flexibility.
Integer Division
In Python 2, 3/2 returns 1 (floor division). In Python 3, 3/2 returns 1.5 (true division). Use // for explicit floor division in Python 3.
String Encoding
Python 2 strings are ASCII by default; you need a u"" prefix for Unicode. Python 3 strings are Unicode by default — a massive improvement for internationalization.
Other Key Differences
- range(): Py2 returns a list; Py3 returns a memory-efficient range object.
- dict methods:
.keys(),.values(),.items()return views in Py3, not lists. - Exceptions:
except Exception, e:in Py2 becomesexcept Exception as e:in Py3. - next():
iterator.next()in Py2 becomesnext(iterator)in Py3. - exec: Statement in Py2, function in Py3.
- Type annotations: Only available in Python 3.5+.
- f-strings: Only available in Python 3.6+.
- Walrus operator (:=): Only available in Python 3.8+.
Python 3.x Version Highlights
- 3.6: f-strings, type hints improvements, async/await
- 3.7: Data classes,
__init_subclass__, dict ordering guaranteed - 3.8: Walrus operator (
:=), positional-only parameters - 3.9: Dict merge operators (
|,|=), built-in generic types - 3.10: Structural pattern matching (
match/case), better error messages - 3.11: 10-60% faster than 3.10, exception groups,
tomllib - 3.12: Per-interpreter GIL (experimental), f-string improvements,
typestatement
Migration Tip
If you encounter Python 2 code, use 2to3 tool (comes with Python) to automatically convert code to Python 3 syntax. Also, futurize from the future package provides more thorough conversions.
Use Cases
Maintaining and migrating legacy Python 2 codebases
Understanding version-specific features for interviews
Choosing the right Python version for new projects
Writing code compatible with specific Python version constraints
Common Mistakes
Using Python 2 print statement syntax in Python 3
Assuming integer division behaves the same in Python 2 and 3
Not handling Unicode properly when migrating from Python 2
Using features from newer Python versions without checking compatibility