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:
from platform import python_version
: This line imports thepython_version
function specifically from theplatform
module. This is generally good practice as it only imports what's needed.print("Current Version of Python interpreter we are using-", python_version())
: This line calls thepython_version()
function, which returns the Python version as a string (e.g., "3.9.7"). Theprint()
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:
import sys
: This line imports thesys
module, giving you access to system-specific variables and functions.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.print("\nVersion info:")
&print(sys.version_info)
: This prints a named tuplesys.version_info
containing the five components of the version number:major
,minor
,micro
,releaselevel
, andserial
. 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.