This tutorial will guide you through the process of understanding, creating, and importing Python modules. Modules are integral to Python programming as they help in organizing code, reusability, and namespace handling.
Step 1: Understanding Python Modules
A Python module is a .py file containing Python definitions and statements. They are simply files with a .py extension that implement a set of functions. Modules are imported using the import keyword.
import mathPractice Exercise
Import the datetime module and print the current date and time.
Show Solution
import datetime
print(datetime.datetime.now()) # prints the current date and timeStep 2: Creating a Python Module
To create a module, simply save the code you want in a file with the file extension .py. For example, let's create a module named mymodule.
def greeting(name):
print('Hello, ' + name)Practice Exercise
Create a module named shapes with a function area_rectangle that calculates the area of a rectangle.
Show Solution
def area_rectangle(length, breadth):
return length * breadth # returns the area of the rectangleStep 3: Importing a Python Module
After creating a module, you can use it by using the import keyword.
import mymodule
mymodule.greeting('John')Practice Exercise
Import the shapes module you created and calculate the area of a rectangle with length 5 and breadth 7.
Show Solution
import shapes
print(shapes.area_rectangle(5, 7)) # prints the area of the rectangleStep 4: Python from...import statement
If you want to directly import a specific function from a module, you can use the from...import statement.
from mymodule import greeting
greeting('John')Practice Exercise
From the shapes module, import the area_rectangle function and calculate the area of a rectangle with length 8 and breadth 3.
Show Solution
from shapes import area_rectangle
print(area_rectangle(8, 3)) # prints the area of the rectangleStep 5: Python dir() Function
The dir() function can be used to find out which functions are implemented in each module.
import math
dir(math)Practice Exercise
Import the datetime module and use the dir() function to list out all the functions in the datetime module.
Show Solution
import datetime
dir(datetime) # prints all the functions in the datetime moduleSign in to take Cornell notes on this lesson — they save automatically and stay with your account.