Modules and Packages
Sometimes, you don't have to write all the code yourself.
For common tasks, it is likely that someone before you has encountered the same problem and has already created a solution.
They have also put that code somewhere online so that other people can benefit from it as well.
This is called a module.
Every module will likely have its own public instructions on how to use it, called its documentation. This is often a website somewhere online.
Let's say you want to find the factorial of a number.
The factorial of a number n
is defined as the product of all the numbers from 1 to n
.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
This function uses recursion, which means that it's calling itself over and over again. Seems a bit complex, doesn't it?
Luckily, there is a built-in module called math
that contains a function called factorial
.
To use the math
module, you first need to import it by adding this line to the top of the file.
import math
Now, if we want to find the factorial of 10, we can just call:
math.factorial(10) # 3628800
To recap, here's what you would do if you did it all by yourself:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
factorial(10)
Here's what you would do if you used the math
module:
import math
math.factorial(10)
Python contains many different built-in modules to make your life easier.
Additionally, the Python community has a ton of modules that you can download from pypi.org. These modules cover everything under the sun.