< previous | Table of Contents | next > |
2.6 LIBRARIES AND PACKAGES
Libraries are collections of pre-written code that developers can use in writing their programs. This makes software composable and means you don't have to reinvent the wheel every time. A library you will interact with throughout the course and have seen plenty of already during this chapter is the Python Standard Library, which includes the essential built-in functions and types and mathematical modules, like math and random.
Each library has documentation explaining how to use the library's contents. Here's a link to the documentation to the Python Standard Library Mathematical functions.
# We have to specify which library we want to use through the import command import math # Accessing the pow() function within the random library to raise x to the power of y power_of = math.pow(3, 4) print(power_of) # We can also specify the specific function that we want to use at the time of importing from math import pow # Accessing the pow() function within the random library to raise x to the power of y power_of = pow(5, 2) print(power_of)
Note that the pow function converts both arguments to type float. This differs from the exponentiation operator **
where such a conversion does not occur.
Commonly, you would only use specific imports if you need only a few functions from a library. If those functions are used frequently, importing them directly can be more straightforward and efficient. If you're using many different library parts, import the whole library. However, in the context of this course, feel free to use it whichever way you feel more comfortable.
KEY THINGS TO REMEMBER
- Libraries are collections of pre-written code that you can utilize in your projects.
- Use the
import
command to import the entire library - Use the
from library import function
command to import a specific function from a library. - Specific imports are best when only a few functions are used and needed frequently.
- Full imports are ideal when multiple functions from a library are used.
< previous | Table of Contents | next > |