Python 2 vs Python 3

By

Understand the difference between Python 2 and Python 3, why Python 2 reached end of life in 2020, and why all new code today should be written in Python 3.

~~~

The short answer: Python 3 is the Python you should use. Python 2 reached end of life in early 2020 and no longer receives updates, not even security fixes.

One key topic to talk about, right from the start, is the Python 2 vs Python 3 discussion.

Python 3 was introduced in 2008, and it’s been in development as the main Python version, while Python 2 continued being maintained with bug fixes and security patches until early 2020.

On that date, Python 2 support was discontinued.

Why did Python 3 break compatibility?

Python 3 fixed design decisions that couldn’t be fixed without breaking existing programs. That’s why the two versions coexisted for over a decade: code written for one often doesn’t run on the other.

The most visible change is print. In Python 2 it was a statement, in Python 3 it’s a function:

# Python 2
print "hello"

# Python 3
print("hello")

Division also changed. In Python 2, dividing two integers returned an integer, silently dropping the decimal part:

# Python 2
5 / 2  # 2

# Python 3
5 / 2   # 2.5
5 // 2  # 2 (floor division, when you want the old behavior)

And strings: in Python 3 every string is Unicode by default. In Python 2 you had to juggle two string types, str and unicode, a constant source of encoding bugs.

How to tell which version you’re running

Check with:

python --version

On many older systems python pointed to Python 2, and Python 3 was available as python3. That’s worth checking before running any code.

Here is the classic trap: you find an old tutorial, copy a Python 2 example, and run it with Python 3:

print "hello"
# SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?

The fix is not installing Python 2. The fix is updating the code, starting with the parentheses.

What about existing Python 2 code?

Many programs are still written using Python 2, and organizations still actively work on those, because the migration to Python 3 is not trivial and those programs would require a lot of work to upgrade those programs. And large and important migrations always introduce new bugs.

So Python 2 survives in maintenance mode inside companies, and that’s the only place you should ever encounter it.

But new code, unless you have to adhere to rules set by your organization that forces Python 2, should always be written in Python 3.

Tagged: Python · All topics
~~~

Related posts about python: