A Python module may contain a set of Python functions or other values and we can easily import those functions or values to another Python program and use them. For example, let’s say the file factorial.py contains a function compute_factorial(). The compute_factorial() function computes the factorial of a given number in the following way:
def compute_factorial(number): if number == 1: return number else: return number * compute_factorial(number – 1)
Please note that the compute_factorial() function here is a recursive function and it computes the factorial of a number using the formula:
n! = n * (n - 1) * (n – 2) * ... 3 * 2 * 1 = n * (n – 1)!
Now, let’s say we have written another program and we need to compute the factorial of a number inside the program. If we use the Python module, then we do not need to write the compute_factorial() function again in the new program. Instead, we can import the compute_factorial() function from factorial.py in the following way:
from factorial import compute_factorial
Here, factorial indicates the file factorial.py and compute_factorial indicates the function compute_factorial() from the file factorial.py.
We can also import all the code from the file factorial.py in the following way:
0 Comments