Python Standard Library
We have already used the
random and
turtle modules to generate random numbers
or to create graphical effects using the turtle. These are part of the
Python 3 Standard Library,
which contains many other useful modules:
https://docs.python.org/3/library/
We can't analyze all of them here; we just need to
be aware of their existence and, if needed,
properly document ourselves,
then use the subroutines of a particular module that can be useful to us!
Ways to Include Modules
To include a module in our program, we've seen that we use the
import directive followed by the library name:
import random
We can include multiple modules in a single command:
import random, turtle
or just some of the subroutines contained in a module:
from random import random, randint, choice
because
we want to be efficient –
we include only what we need.
The math Module - Be Self-Taught!
Let's assume we need to calculate the expression:
G(x) = sin(x) + cos(x) + cos(2*x)
for
x
, a value read from the keyboard.
First, I try a simple formula in the console:
but I immediately notice that the
cosine function
is not provided by default by the Python 3 interpreter. I open the standard library web page and notice that there is a
math module:
Wonderful! There, besides
cos, I find a lot of other useful mathematical functions and study a bit about them
(there are dozens, and I might need one of them later).
I return to my program and first import the module, then write the rest of the code that solves the problem:
You can download the source code from [
here].
Of course, it would have been optimal to include only the functions used from the module:
from math import sin, cos
Simple and elegant.