On the first of October 2020 I have written the blog post "Install Python 3.8 on a Raspberry Pi". That article about how to install Python 3.8 on a Raspberry Pi got a lot of attention. A lot of people read my article an started using Python 3.8. But now there is Python 3.9 so I thought why not write an article on how to install Python 3.9 on a Rasperry Pi!

Raspberry PI What?

The Raspberry Pi is a low cost, credit-card sized computer that you can plug into a computer monitor, mouse and keyboard. It is a capable little device that enables people of all ages to explore computing, and to learn how to program in languages like Scratch and Python. The Raspberry runs on linus and has it's own distro called Raspberry PI OS.

The Raspberry Pi OS is the Foundation’s official supported operating system and comes pre-installed with 2 versions of Python. Last time I checked 2.7.x and 3.5.x. And as you want to develop in Python 3, you need to specify the version of Python you are using each time and that is annoying! So, lets install the 3.9 version and make it your default!

Install Python 3.9 on a Raspberry PI

First make sure you can ssh to your Raspberry Pi. The default SSH user and password on Raspberry Pi OS are:
– login: pi
– password: raspberry

You cannot login to your Raspberry Pi with SSH? Read this!

First install the dependencies needed to build:

sudo apt-get update

sudo apt-get install -y build-essential tk-dev libncurses5-dev libncursesw5-dev libreadline6-dev libdb5.3-dev libgdbm-dev libsqlite3-dev libssl-dev libbz2-dev libexpat1-dev liblzma-dev zlib1g-dev libffi-dev

Updating.... this takes a while, grab a coffee and get me one to!!

Next download the latest python version, untar it and compile it.

wget https://www.python.org/ftp/python/3.9.0/Python-3.9.0.tar.xz
tar xf Python-3.9.0.tar.xz
cd Python-3.9.0
./configure --prefix=/usr/local/opt/python-3.9.0
make -j 4

Building and compiling python can take a while (depends on the Raspberry Pi you have and the amount of memory). And when done, lets install what was build!

sudo make altinstall

Lets do a cleanup and remove the files we don't need anymore

cd ..
sudo rm -r Python-3.9.0
rm Python-3.9.0.tar.xz
. ~/.bashrc

Finally! Let's make Python 3.9 the default version, make aliases by:

sudo update-alternatives --config python

And verify:

python -V

If you still have a 2.x or 3.x version and not the 3.9 version, or when you get an error message do as following.

nano ~/.bashrc

Go to the last line (arrow down) and find something like:

alias python=/usr/bin/python-3.8

And change this to

alias python=/usr/local/opt/python-3.9.0/bin/python3.9

Do a CTRL+X and CTRL+Y

Then in the terminal do:

. ~/.bashrc

This refreshes the bashrc in your terminal

Verify the Python version by:

python -V

and hopefully you see:

Python 3.9.0

Your are ready to go!

Happy programming!! Questions? Let me know in the comments below!