Get the Python version number from code

Outputting the Python version on the shell is straightforward, and you do it just like how you get the version of other programs.

$ python --version
Python 3.8.5

Getting this version number in a script can be useful as well. But you have multiple options there.

One coming close to the one we saw above is by using the python_version() function from the platform module.

from platform import python_version

print(python_version())
# => 3.8.5

More detailed ones are found in the sys module.

from sys import version

print(version)
# => 3.8.5 (default, Jul 28 2020, 12:59:40)
# => [GCC 9.3.0]

This shows a more detailed string containing version info. Together with the compiler that was used.

If you programmatically want to do something with the version number you can better use something other than sys.version().

That something else might be sys.version_info. It returns always five components of the version number. Nicely in a tuple.

from sys import version_info

print(version_info)
# => sys.version_info(major=3, minor=8, micro=5, releaselevel='final', serial=0)

Checking for python version 2 or 3

If checking for Python version 2 is still a thing, you can easily do it with the version_info function.

from sys import version_info

if version_info.major == 3:
    print('Running Python 3')
elif version_info.major == 2:
    print('Running Python 2')

See Also

6 Non-Programming Books for Programmers