A module is a collection of Python code that can be imported for use in your code. When a module is imported, the code in the module is executed, which makes it possible to use the functions and variables defined in the module. Python includes several modules in its standard library and you can also create and install more. In this section, we will sample a few of the standard library modules so you can get a feel for how modules work.
We will be using the
sys module in this section as an example.
sys module provides access to some variables
such as the Python version and the current platform the code is running on.
To use a module, you must first import it.
You can import a module using the
import keyword. After importing a module, you can access its functions and variables by using the dot operator.
For example, to print the current Python version, you can do the following:
import sys print(sys.version)
If you only want to use a specific function or variable from a module, you can import it directly using
from sys import version
And if you want to import multiple functions or variables from a module, you can do the following:
from sys import version, platform
You can even change the name of what you are importing.
import sys as system from sys import version as python_version from sys import version, platform as sys_version, sys_platform
sys module to print the current Python version and platform.
random module provides functions for generating
random numbers amount other things. The
function imported from a module. The
takes two integers as arguments and will return a random integer
between the two numbers. For example, the following code will print
a random number between 1 and 100, including 1 and 100.
from random import randint print(randint(1, 100))
randint create a random number
x from 1 to 4. Then, print the number as a word.
For example, if the number is 1, print
math module is another useful module to know.
It provides access to many mathematical functions and constants
that you would find on a calculator. Such as
import math print(math.pi)
sqrt function, print the square root of
os module provides access to functions
that allow you to interact with the operating system,
like working with files and directories.
Another feature is the ability to read environment variables
set by the operating system.
import os print(os.getenv("PATH"))
os module, print the environment variables of the