Libraries
A library is a place we go to borrow books written by others and use them for many different purposes. The author of a book shares his ideas, findings, and work with others so we can benefit from the collection of works done by others and produce our own works. Similar to the idea of a physical library 📚, programming languages often have libraries that have a lot of programs we can borrow and use in our programs. This is to prevent writing the same programs over and over again. Python also has many libraries. We will explore some of those libraries that are basic and easy to use, especially for scientists.
The Math library
We can tell Python that we want to borrow programs from a specific library using the import
keyword. After importing a library, we can use some of the functions or constants defined in the library. For example, we can borrow the pi
number from the math library:
import math
print(math.pi)
The Math library has many other useful functions and constants:
x = 1.6
y = math.floor(x)
y = math.ceil(x)
x = 6
y = math.factorial(x)
y = math.exp(x)
y = math.log(x,10)
y = math.sqrt(x)
r = math.radians(90) #convert from degrees to radians
d = math.degrees(r) #convert from radians to degrees
math.cos(r) #x is in radians
math.sin(r)
print(math.pi)
print(math.e)
print(math.tau)
print(math.inf)
print(math.nan)
Other ways to use libraries
Sometimes we wish to import a specific function from a library. We can do this by using the from
keyword.
from math import pi
print(pi)
In this program, we imported the name pi
from the math
library. We can use pi
directly since we used the from
keyword. This can work with any library name.
We could also import all the names in a library:
from math import *
print(pi)
print(e)
print(factorial(4))
Using *
we are telling the compiler to use all the names in the library directly without using the name of the library as we did earlier.