In this tutorial you will learn:
We have been using Modules for quite a while now. We noticed that after importing the modules we had access to more functions in our code. So a Module is a package that contains different sets of functions, classes and variables. Whenever be bring the module in our code we get those extra functions by just writing a single line of code at the top.
Modules in Python
Modules in Python also contain functions and statements. We use modules to split the code into separate files which could then be imported to another file with just one line import statement. Any Python file can serve as a Module. It gives us a lot of flexibility and allow code reusability.
Creating your own Modules
Creating a Module in Python is very simple we can simply create a file with .py extension and then import the file into another file. Let’s create a file called “calculator.py”
Example:Let's create a simple printing modules that prints items of a listing using for loop. Save this in a file named "printing.py"
- def printElementsOf(list):
- for element in list:
- print("Element is ", element)
- def printGreetings():
- print("Hello user welcome to printing module")
- def multiply(x, y):
- return x * y
- def divide(x, y):
- return x / y
- def subtract(x, y):
- return x - y
- def add(x, y):
- return x + y
- def factorial(num):
- if num == 1:
- return 1
- return num * factorial(num-1)
- def fibonacci(n):
- if n <= 1:
- return 1
- return(fibonacci(n-1) + fibonacci(n-2))
Using your own Modules
Now let’s use our newly created modules in our new created Python file. We know that we first need to import the Module and then we will have access to all the methods and functions of that module.
Example:There are different ways to import a module so we will use different ways for every module we created. Using the printing module we simply use the import statement.
- import printing
- print("\n\n** Printing Module ** ")
- myList = ["Test", "Python", "Programming"]
- from calculator import multiply, divide, add, subtract
- print("\n\n ** Calculator import using from **")
- print("Sum of 5 and 6", add(5,6))
- print("Subtraction of of 20 and 5", subtract(20,5))
- print("Multiplication of 10 and 4", multiply(10,4))
- import fib_fact as ff
- print("\n\n ** Fib Fact renamed import **")
- print("Factorial of 4", ff.factorial(4))
- print("Fibonacci of 10", ff.fibonacci(10))
Finding contents of a Module
To find the contents of a Module is very simple we simply need to call the dir function by passing in the module name.
- import calculator<br />