A good guide on how to install whatever version of Python you want, on Debian, can be found in this post on StackExchange and on sobyte. However, the compact version of it is to move into your Downloads folder and run the following commands.
Side note: to be able to build all optional modules you will need to install the following dependencies:
sudo apt install \
build-essential \
gdb \
lcov \
libbz2-dev \
libffi-dev \
libgdbm-dev \
libgdbm-compat-dev \
liblzma-dev \
libncurses5-dev \
libreadline6-dev \
libsqlite3-dev \
libssl-dev \
lzma \
lzma-dev \
tk-dev \
uuid-dev \
zlib1g-dev
A list of possible Python versions is available here, but for this guide we will install version 3.9.16.
wget https://www.python.org/ftp/python/3.9.16/Python-3.9.16.tgz
tar xvf Python-3.9.16.tgz && cd Python-3.9.16
./configure --enable-optimizations --with-lto=yes \
--enable-loadable-sqlite-extensions \
--enable-shared \
--prefix=/usr/local \
LDFLAGS="-Wl,-rpath /usr/local/lib"
make -j$(nproc)
sudo make altinstall
To then test if it worked, the following command should spell out the version number you just installed above.
python3.9 --version