Python 3 was released at the end of 2008 and marks a major update to Python. Some of the changes introduced in Python 3 break backward compatibility with earlier versions of Python, so to ease the transition for current Python developers, the development of Python 2 has continued in parallel with the newer Python 3.
In this chapter, we’ll summarize some of the main changes to Python 3 and also explain how you can convert a Python 2 program to Python 3.
Python 3 introduces many new features; the following are some of the most visible:
Python 3’s print
function is indeed a function. In Python 2, print
was a language construct, similar to if
and for
. The problem with Python 2’s print
was that it was difficult to modify—for example, changing print
statements to print to a file instead of the console is much easier in Python 3 because you can just reassign the print
function.
Dividing integers in Python 3 works as you would expect when fractions are involved:
Python3>>> 1/2 0.5
However, Python 2 chops off all digits after the decimal when dividing integers:
Python2>>> 1/2 0
While Python 2’s way of dividing integers appears in other programming languages, many programmers find it counterintuitive and the cause of subtle errors.
Python 2 has two kinds of classes: old-style classes and new-style classes. Python 3 drops old-style classes completely.
Python 3 renames a couple of important functions: The input
and range
functions are called raw_input
and xrange
in Python 2.
The format strings described in Chapter 9 exist only in Python 3, and not Python 2. Python 2 only has string interpolation with the %
operator.
Many other technical changes have been made in Python 3. For a complete list of differences, see “What’s New in Python 3.0” (http://docs.python.org/dev/3.0/whatsnew/3.0.html).
Python developers have been quite aware of the difficulties of moving to a new version of Python, and so have provided a couple of tools to make the conversion easier.
The first tool is named 2to3 (http://docs.python.org/library/2to3.html), and is a program that does most of the work of converting Python 2 programs into equivalent Python 3 programs.
Another useful tool is Python 2, version 2.6 and above, which can provide warnings when you are using features that have changed in Python 3.
When deciding what version of Python to use—2 or 3—there are a few things to take into consideration:
If you must work with programs that are written in Python 2, then it would make most sense to use to use Python 2 (2.6 or higher) and gradually move to Python 3.
Some special-purpose libraries may only work with one version of Python, and so if you need to use one of those, your choice of Python may be constrained.
If you are just starting out as a programmer, and have no old Python programs to maintain or special-purpose libraries that you must use, then Python 3 is probably the best choice.
3.136.236.17