Chapter 5. Python Basics
5.0 Introduction
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
Problem
You need to use Python but are unsure which version to use.
Solution
Use Python 3 until you face a problem that is best solved by reverting to version 2.
To install Python 2 on Raspberry Pi OS, run the following commands:
$ sudo apt update $ sudo apt install python2
You can then run Python 2 using the command python2
.
Discussion
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. Python 3 (the default for Raspberry Pi OS) is run by using either of the commands python
or 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 only when I need to because of compatibility problems.
See Also ...
Get Raspberry Pi Cookbook, 4th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.