Modules in Python for Beginners
Modules extend Python’s capabilities and simplify programming. For example, the math module helps with numerical operations, while the datetime module handles dates and times.
You can find descriptions of the modules included in the Python standard library on the official website.
Beginners might feel overwhelmed by the number of modules available, but there’s no need to memorize them all. Use modules as needed.
For instance, if you’re dealing with complex math calculations, import a module that supports the required operations. This way, you won’t need to recreate existing solutions.
Third-party modules can be written in Python, C, or C++, which can significantly boost performance.
Let’s try importing the math module into our program. Use the import command followed by the module name.
import math
Now you can use all the functions in this module. Write the module name, a dot, and the function name.
For example, to get the value of π:
import math
print(math.pi)
or the cosine of one:
import math
print(math.cos(1))
Let’s look at examples of using standard library modules. Import a module for working with time and another for generating random numbers:
import time
import random
while True:
print(random.randint(1, 100))
time.sleep(1)
This program outputs a random integer from 1 to 100 with a one-second pause.