Chapter 5. Python Basics
Although many languages can be used to program the Raspberry Pi, Python is the most popular. In fact, the Pi in Raspberry Pi is inspired by the word python.
In this chapter, you’ll find a host of recipes to help you start programming with Raspberry Pi.
5.1 Deciding Between Python 2 and Python 3
You need to use Python but are unsure which version to use.
Use both. Use Python 3 until you face a problem that is best solved by reverting to version 2.
Although Python’s most recent version, Python 3, has been around for years, you’ll find that a lot of people still use Python 2. In fact, in the Raspbian distribution, both versions are supplied, and version 2 is just called Python, whereas version 3 is called Python 3. And Python 3 is run by using the command
python3. The examples in this book are written for Python 3 unless otherwise stated. Most will run on both Python 2 and Python 3 without modification.
This reluctance on the part of the Python community to ditch the older version is largely because Python 3 introduced some changes that broke compatibility with version 2. As a result, some of the huge body of third-party libraries developed for Python 2 won’t work under Python 3.
My strategy is to write in Python 3 whenever possible, reverting Python 2 when I need to because of compatibility problems.
For a good summary of the Python 2 versus Python 3 debate, see the Python wiki.