In this section, we will find out which versions of Python you have installed on your Raspberry Pi. As we will discover, there are two versions of Python that come pre-installed on Raspbian OS. Unix-based operating systems (such as Raspbian OS) typically have Python version 2 and 3 pre-installed because there are operating-system-level utilities built with Python.
To find out which versions of Python you have on your Raspberry Pi, follow these steps:
-
Open a new Terminal and execute the python --version command:
$ python --version
Python 2.7.16
In my example, we see that Python version 2.7.16 has been installed.
-
Next, run the python3 --version command:
$ python3 --version
Python 3.7.3
In my example, we see that the second version of Python (that is, python3, with the 3) that is installed is version 3.7.3.
Don't worry if the minor versions (the numbers .7.16 after the 2 and .7.3 after 3) are not the same; it is the major versions 2 and 3 that are of interest. Python 2 is a legacy version of Python, while Python 3 is the current and supported version of Python at the time of writing. When we are starting a new Python development, we will practically always use Python 3 unless there are legacy issues we need to contend with.
If you are an experienced Python programmer, you may be able to discern whether a script is written for Python 2 or 3, but it's not always obvious by simply looking at a piece of code. Many new-to-Python developers experience frustrations by mixing up Python programs and code fragments that are meant for different Python versions. Always remember that code written for Python 2 is not guaranteed to be upward-comparable with Python 3 without modification.
A quick tip I can share to visually help to determine which Python version a code fragment is written for (if the programmer has not made it clear in the code comments) is to look for a print statement.
If you look at the following example, you will see that there are two print statements. The first print statement without the parentheses is a give-away that it will only work with Python 2:
print "Hello" # No parentheses - This only works in Python 2, a dead give-away that this script is for Python 2.
print("Hello") # With parentheses - this will work in Python 2 and Python 3
Of course, you can always run the code against both Python 2 and 3 and see what happens.
We have now seen that there are two Python versions available by default on Raspbian OS, and made mention that there are system-level utilities that are written in Python that reply on these versions. As Python developers, we must take care not to disrupt the global Python installations as this can potentially break system-level utilities.
We will now turn our attention to a very important Python concept, the Python virtual environment, which is the way we isolate or sandbox our own Python projects from the global installation.