Lesson 15: Modules and Packages

Jun 19, 2023 | Uncategorized | 0 comments

Home 9 Uncategorized 9 Lesson 15: Modules and Packages

Modules and packages are essential concepts in Python that help organize and structure code into reusable and manageable components. A module is a single file containing Python definitions, functions, and classes. A package is a collection of modules organized in a directory hierarchy.

Let’s explore modules and packages in Python:

# Importing modules
import math

# Using functions from the math module
print("Square root of 16:", math.sqrt(16))
print("Value of pi:", math.pi)

# Importing specific functions from a module
from random import randint, choice

# Using functions from the random module
print("Random number between 1 and 10:", randint(1, 10))
print("Random choice from a list:", choice(["apple", "banana", "cherry"]))

# Importing an entire module with an alias
import datetime as dt

# Using the datetime module with the alias
current_date = dt.date.today()
print("Current date:", current_date)

# Importing a module from a package
from mypackage import mymodule

# Using a function from the imported module
mymodule.greet()

# Creating a package structure
# mypackage/
#     __init__.py
#     mymodule.py

# Contents of mymodule.py
# def greet():
#     print("Hello, from mymodule!")

# Contents of __init__.py (can be empty)

Explanation:

  • We can import modules using the import keyword, followed by the module name.
  • We can access the functions, classes, and variables from the imported module using dot notation (module_name.function() or module_name.variable).
  • We can import specific functions from a module using the from keyword, followed by the module name and the specific function names separated by commas.
  • We can assign an alias to a module using the as keyword, allowing us to use a shorter name to reference the module.
  • We can import modules from packages by specifying the package name and the module name separated by dot notation.

Now it’s time for a practical task:

Task 15:

Create a package called shapes with two modules, rectangle and circle. In the rectangle module, define a function calculate_area() that calculates the area of a rectangle given its width and height. In the circle module, define a function calculate_area() that calculates the area of a circle given its radius. Import both modules and calculate the areas of a rectangle and a circle.

Once you’ve completed the task, you can proceed to the next lesson.

Join The FFF Newsletter

Future Flow Forecast

Future Flow Forecast

Joinย the number one AI newsletter and learn how to be at the forefront of the latest discoveries. This is your "dotcom bubble" chance!

You have Successfully Subscribed!