askvity

How to write a Python program to get the Python version you are using?

Published in Python Programming 3 mins read

You can retrieve the Python version you are currently using with a simple Python program by leveraging the platform module or the sys module. Here's how:

Using the platform Module:

The platform module provides access to underlying platform's identifying data, including the Python version.

from platform import python_version

print("Current Version of Python interpreter we are using-", python_version())

Explanation:

  1. from platform import python_version: This line imports the python_version function specifically from the platform module. This is generally good practice as it only imports what's needed.
  2. print("Current Version of Python interpreter we are using-", python_version()): This line calls the python_version() function, which returns the Python version as a string (e.g., "3.9.7"). The print() function then displays this version number with a descriptive message.

Using the sys Module:

The sys module provides access to system-specific parameters and functions, including the Python version information.

import sys

print("Python version:")
print (sys.version)

print("\nVersion info:")
print (sys.version_info)

Explanation:

  1. import sys: This line imports the sys module, giving you access to system-specific variables and functions.
  2. print("Python version:") & print(sys.version): This displays the Python version string. sys.version returns a string containing the version number, build number, and compiler used.
  3. print("\nVersion info:") & print(sys.version_info): This prints a named tuple sys.version_info containing the five components of the version number: major, minor, micro, releaselevel, and serial. This can be useful for more programmatic version comparisons.

Example Output (using sys module):

Python version:
3.9.7 (default, Sep 16 2021, 13:09:58) 
[GCC 7.5.0]

Version info:
sys.version_info(major=3, minor=9, micro=7, releaselevel='final', serial=0)

Choosing the Right Method:

  • platform.python_version(): This is the simplest way to get just the basic version number as a string (e.g., "3.9.7"). It is recommended for ease of use when all you need is the version string itself.
  • sys.version: This provides a more detailed string representation of the version, including build information.
  • sys.version_info: This gives you a named tuple with the individual components of the version number, useful for programmatic comparisons and version checks.

In most cases, platform.python_version() provides the simplest and most readable way to get the Python version string.

Related Articles