Python Libraries¶
Objectives¶
- 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
Most of the power of a programming language is in its libraries.¶
- 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][stdlib] is an extensive suite of modules that comes with Python itself.
- Many additional libraries are available from [PyPI][pypi] (the Python Package Index).
- We will see later how to write new libraries.
Libraries and modules¶
A library is a collection of modules, but the terms are often used interchangeably, especially since many libraries only consist of a single module, so don't worry if you mix them.
In [2]:
import math
print('pi is', math.pi)
print('cos(pi) is', math.cos(math.pi))
pi is 3.141592653589793 cos(pi) is -1.0
Import specific items from a library module to shorten programs.¶
- Use
from ... import ...to load only specific items from a library module. - Then refer to them directly without library name as prefix.
In [3]:
from math import cos, pi
print('cos(pi) is', cos(pi))
cos(pi) is -1.0
Create an alias for library¶
- Use
import ... as ...to give a library a short alias while importing it. - Then refer to items in the library using that shortened name.
In [10]:
import math as m
print('cos(pi) is', m.cos(m.pi/4))
cos(pi) is 0.7071067811865476
In [9]:
import numpy as np
print('cos(pi) is', np.cos(m.pi/4))
cos(pi) is 0.7071067811865476
Use with caution¶
- Aliases can make programs harder to understand, since readers must learn your program's aliases.
Excercise¶
- Find a standard library that can help you select a random character from a string.
- Try writing a code snippet that uses a function from a library that selects a random character from the string
bases = 'ACTTGCTTGAC'
Note: You may use AI assistance, but you should be able to explain what the code does!
In [ ]:
import random
random.choice(
- Fill in the blanks so that the program below prints
90.0
import math as m
angle = ____.degrees(____.pi / 2)
print(____)
In [ ]:
Takeaways¶
- Most of the power of a programming language is in its libraries.
- A program must import a library module in order to use it.
- Use
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.