About Lesson
Modules
- What are Modules?: Modules are files containing Python code. They help organize our program by separating related functionality.
- Modules and Libraries: Import external modules and use their functionality.
- Creating a Module:
- Let’s create a simple module named
math_operations.py
:Python# math_operations.py def add(a, b): return a + b def subtract(a, b): return a - b
- Let’s create a simple module named
- Using a Module:
- In another Python file, we can import and use the functions from our module:
Python
# main.py import math_operations result1 = math_operations.add(5, 3) result2 = math_operations.subtract(10, 4) print(f"Addition result: {result1}") print(f"Subtraction result: {result2}")
- In another Python file, we can import and use the functions from our module:
Standard Library Modules
- Python provides a rich set of standard library modules for common tasks.
- Example: Using the
math
module to get the value of π (pi):Pythonimport math print(f"The value of π is approximately {math.pi}")
Best Practices
- Keep functions small and focused.
- Use meaningful function names.
- Organize related functions into modules.
- Avoid naming conflicts by using unique module names.
By mastering functions and modules, you’ll write cleaner, more maintainable code. Keep practicing and building!
Join the conversation