Overview
This lecture introduces Python modules and import statements, covering both built-in and custom modules, and demonstrates how to use them for modular programming.
Python Modules & Import Statements
- Python uses modules to organize code into separate files that can be reused across programs.
- The import statement is used at the top of a script to include modules.
- Example:
import math imports the math module for mathematical functions.
Built-in vs. External Modules
- Built-in modules like math and os come with Python and can be imported directly.
- External modules, such as "pygame," must be downloaded and installed before importing.
- Example:
import os gives access to functions for file paths and system operations.
Using Module Functions
- Call functions from a module using the syntax: ModuleName.FunctionName (e.g.,
math.sqrt(9) gives 3).
math.pi provides the value of π; math.degrees() converts radians to degrees; math.radians() does the reverse.
Creating and Importing Custom Modules
- Create a custom module by making a new
.py file in the same directory as your main script.
- Define functions in the custom module file (e.g.,
def my_func(x): return x + 5).
- Import your custom module with
import mymodule, then call functions using mymodule.my_func(6).
- Multiple functions can be defined and accessed within one module.
Modular Programming in Python
- Modular programming helps organize large programs by separating code into reusable modules.
- Modules keep code organized and reusable across different Python scripts.
Key Terms & Definitions
- Module — A Python file containing functions and classes to be imported and reused.
- Import Statement — The syntax (
import modulename) that brings a module into your script.
- Built-in Module — Modules that are included with Python (e.g., math, os).
- External Module — Modules that need to be installed separately (e.g., pygame).
- Custom Module — A user-created Python file with reusable code.
Action Items / Next Steps
- Practice importing and using both built-in and custom modules.
- Explore the list of available built-in Python modules on the official Python website.
- Optional: Research how to install and use external modules like pygame.