Last updated on 2023-05-02 | Edit this page
Estimated time 20 minutes
- How can I use software that other people have written?
- How can I find out what that software does?
- Explain what software libraries are and why programmers create and use them.
- Write programs that import and use modules from Python’s standard library.
- Find and read documentation for the standard library interactively (in the interpreter) and online.
- A library is a collection of files (called
modules) that contains functions for use by other programs.
- May also contain data values (e.g., numerical constants) and other things.
- Library’s contents are supposed to be related, but there’s no way to enforce that.
- The Python standard library is an extensive suite of modules that comes with Python itself.
- Many additional libraries are available from PyPI (the Python Package Index).
- We will see later how to write new libraries.
importto load a library module into a program’s memory.
- Then refer to things from the module as
- Python uses
.to mean “part of”.
- Python uses
math, one of the modules in the standard library:
import math print('pi is', math.pi) print('cos(pi) is', math.cos(math.pi))
pi is 3.141592653589793 cos(pi) is -1.0
- Have to refer to each item with the module’s name.
math.cos(pi)won’t work: the reference to
pidoesn’t somehow “inherit” the function’s reference to
- Works just like help for a function.
Help on module math: NAME math MODULE REFERENCE http://docs.python.org/3/library/math The following documentation is automatically generated from the Python source files. It may be incomplete, incorrect or include features that are considered implementation detail and may vary between Python implementations. When in doubt, consult the module reference at the location listed above. DESCRIPTION This module is always available. It provides access to the mathematical functions defined by the C standard. FUNCTIONS acos(x, /) Return the arc cosine (measured in radians) of x. ⋮ ⋮ ⋮
from ... import ...to load only specific items from a library module.
- Then refer to them directly without library name as prefix.
from math import cos, pi print('cos(pi) is', cos(pi))
cos(pi) is -1.0
import ... as ...to give a library a short alias while importing it.
- Then refer to items in the library using that shortened name.
import math as m print('cos(pi) is', m.cos(m.pi))
cos(pi) is -1.0
- Commonly used for libraries that are frequently used or have long
- E.g., the
matplotlibplotting library is often aliased as
- E.g., the
- But can make programs harder to understand, since readers must learn your program’s aliases.
help(math)we see that we’ve got
pow(x,y)in addition to
sqrt(x), so we could use
pow(x, 0.5)to find a square root.
sqrt(x)function is arguably more readable than
pow(x, 0.5)when implementing equations. Readability is a cornerstone of good programming, so it makes sense to provide a special function for this specific common case.
Also, the design of Python’s
math library has its origin
in the C standard, which includes both
pow(x,y), so a little bit of the history of programming is
showing in Python’s function names.
You want to select a random character from a string:
- Which standard library module could help you?
- Which function would you select from that module? Are there alternatives?
- Try to write a program that uses the function.
The random module seems like it could help.
The string has 11 characters, each having a positional index from 0
to 10. You could use the
functions to get a random integer between 0 and 10, and then select the
bases character at that index:
from random import randrange = randrange(len(bases)) random_index print(bases[random_index])
or more compactly:
from random import randrange print(bases[randrange(len(bases))])
Perhaps you found the
function? It allows for slightly less typing but might be a bit harder
to understand just by reading:
from random import sample print(sample(bases, 1))
Note that this function returns a list of values. We will learn about lists in episode 11.
The simplest and shortest solution is the
function that does exactly what we want:
from random import choice print(choice(bases))
Rearrange the following statements so that a random DNA base is printed and its index in the string. Not all statements may be needed. Feel free to use/add intermediate variables.
="ACTTGCTTGAC" basesimport math import random = random.randrange(n_bases) ___ = len(bases) ___ print("random base ", bases[___], "base index", ___)
import math import random = "ACTTGCTTGAC" bases = len(bases) n_bases = random.randrange(n_bases) idx print("random base", bases[idx], "base index", idx)
Importing the math module (
import math as m = m.degrees(m.pi / 2) angle print(angle)
can be written as
import math = math.degrees(math.pi / 2) angle print(angle)
Since you just wrote the code and are familiar with it, you might actually find the first version easier to read. But when trying to read a huge piece of code written by someone else, or when getting back to your own huge piece of code after several months, non-abbreviated names are often easier, except where there are clear abbreviation conventions.
Match the following print statements with the appropriate library calls.
print("sin(pi/2) =", sin(pi/2))
print("sin(pi/2) =", m.sin(m.pi/2))
print("sin(pi/2) =", math.sin(math.pi/2))
from math import sin, pi
import math as m
from math import *
- Library calls 1 and 4. In order to directly refer to
piwithout the library name as prefix, you need to use the
from ... import ...statement. Whereas library call 1 specifically imports the two functions
pi, library call 4 imports all functions in the
- Library call 3. Here
piare referred to with a shortened library name
math. Library call 3 does exactly that using the
import ... as ...syntax - it creates an alias for
mathin the form of the shortened name
- Library call 2. Here
piare referred to with the regular library name
math, so the regular
import ...call suffices.
Note: although library call 4 works, importing all
names from a module using a wildcard import is not recommended as it makes it
unclear which names from the module are used in the code. In general it
is best to make your imports as specific as possible and to only import
what your code uses. In library call 1, the
statement explicitly tells us that the
sin function is
imported from the
math module, but library call 4 does not
convey this information.
from math import degrees, pi = degrees(pi / 2) angle print(angle)
Most likely you find this version easier to read since it’s less
dense. The main reason not to use this form of import is to avoid name
clashes. For instance, you wouldn’t import
degrees this way
if you also wanted to use the name
degrees for a variable
or function of your own. Or if you were to also import a function named
degrees from another library.
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-1-d72e1d780bab> in <module> 1 from math import log ----> 2 log(0) ValueError: math domain error
- The logarithm of
xis only defined for
x > 0, so 0 is outside the domain of the function.
- You get an error of type
ValueError, indicating that the function received an inappropriate argument value. The additional message “math domain error” makes it clearer what the problem is.
- Most of the power of a programming language is in its libraries.
- A program must import a library module in order to use it.
helpto learn about the contents of a library module.
- Import specific items from a library to shorten programs.
- Create an alias for a library when importing it to shorten programs.