• Discover
  • Collections
  • Board
  • Create
  • Profile
  • Settings
Paths

Lesson 4.3: Introduction to Modules and Importing

Lesson 4.3: Introduction to Modules and Importing

4 min read

As your Python programs grow larger, putting all your code in a single file becomes unwieldy. Modules provide a way to organize your code into separate .py files, making your programs more manageable, reusable, and readable. A module is simply a file containing Python definitions and statements.

What are Modules?

  • A module is a .py file that contains Python code (functions, classes, variables, etc.).
  • When you import a module, you gain access to its contents in your current script.
  • Python has a rich standard library of built-in modules (e.g., math, random, datetime).
  • You can also create your own modules.

Creating Your Own Module

Let's create a simple module. Save the following code in a file named my_calculator.py:

python
# my_calculator.py def add(a, b): """Returns the sum of two numbers.""" return a + b def subtract(a, b): """Returns the difference of two numbers.""" return a - b def multiply(a, b): """Returns the product of two numbers.""" return a * b def divide(a, b): """Returns the division of two numbers, handles division by zero.""" if b == 0: return "Error: Cannot divide by zero!" return a / b PI = 3.14159

Importing Modules

To use the functions and variables defined in my_calculator.py in another Python script (e.g., main_app.py), you need to import it. Make sure both files are in the same directory for Python to find my_calculator.py easily.

  1. import module_name This is the most common way. It imports the entire module, and you access its contents using module_name.item_name.

main_app.py:

python
import my_calculator print(my_calculator.add(10, 5)) # Output: 15 print(my_calculator.subtract(10, 5)) # Output: 5 print(my_calculator.PI) # Output: 3.14159 # Using a function that handles an error print(my_calculator.divide(10, 0)) # Output: Error: Cannot divide by zero!

  1. import module_name as alias If the module name is long, or you want to avoid name clashes, you can give it an alias.
python
import my_calculator as mc print(mc.add(7, 3)) print(mc.multiply(4, 2))

  1. from module_name import item1, item2, ... This imports specific functions or variables directly into your current namespace. You can then use them without the module_name. prefix.
python
from my_calculator import add, PI print(add(100, 20)) print(PI) # print(subtract(50, 10)) # This would cause a NameError, as subtract was not imported

  1. from module_name import * (Avoid in most cases) This imports all public names from the module into your current namespace. While convenient, it can lead to name clashes (where a function in the module has the same name as one you defined or imported elsewhere) and makes it harder to tell where a function or variable came from. It's generally discouraged in production code.
python
from my_calculator import * print(add(2, 2)) print(subtract(5, 1)) print(PI)

Python Standard Library Modules

Python comes with many useful built-in modules.

For example:

  • math: Provides mathematical functions (e.g., sqrt, ceil, floor, pi).
  • random: For generating random numbers (e.g., random.randint, random.choice).
  • datetime: For working with dates and times.
python
import math import random print(math.sqrt(16)) # Output: 4.0 print(math.pi) # Output: 3.141592653589793 print(random.randint(1, 10)) # Output: A random integer between 1 and 10 (inclusive)

Modules are essential for building larger, well-structured applications. They promote code reusability and maintainability by allowing you to break your programs into logical, self-contained units.

Key Takeaways:

  • Modules (.py files) help organize Python code into reusable units.
  • Use import module_name to access module contents via module_name.item.
  • Use import module_name as alias for shorter names.
  • Use from module_name import item to bring specific items into the current namespace directly.
  • Avoid from module_name import * due to potential name clashes.
  • Leverage Python's extensive standard library (e.g., math, random).
End of lesson
👏Well done!
Previous Lesson
Lesson 4.2: Scope of Variables (Local vs. Global)
Next Lesson
Quiz: Module 4: Functions and Modules

Course Content

0% Complete0/22 Lessons

Lesson 1.1: What is Python? History, Features, and Applications

Lesson 1.2: Setting Up Your Python Environment

Lesson 1.3: Your First Python Program: "Hello, World!" and Basic Syntax

Quiz

Lesson 4.1: Defining and Calling Functions. Parameters and Return Values.

Lesson 4.2: Scope of Variables (Local vs. Global)

Lesson 4.3: Introduction to Modules and Importing

Quiz

Course Content

0% Complete0/22 Lessons

Lesson 1.1: What is Python? History, Features, and Applications

Lesson 1.2: Setting Up Your Python Environment

Lesson 1.3: Your First Python Program: "Hello, World!" and Basic Syntax

Quiz

Lesson 4.1: Defining and Calling Functions. Parameters and Return Values.

Lesson 4.2: Scope of Variables (Local vs. Global)

Lesson 4.3: Introduction to Modules and Importing

Quiz