Modules
Introduction to Python
Getting Started
Comments
Variables
Data Types
Type Casting
Input and Output
Operators
Strings
Booleans
Conditional Statements
While Loop
For Loop
Loop Control Statements
Lists
Tuples
Sets
Dictionaries
Functions
Function Arguments and Return Values
Variable Scope
Recursion
Lambda Functions
Arrays and Python Lists
Modules
Dates and Math
String Formatting
File Handling
Try and Except
Classes and Objects
Inheritance
Iterators
JSON
RegEx
Modules
Definition: A module is a file containing Python definitions and statements (such as functions, classes, and variables). Essentially, it is a code library that you can include in your project to reuse existing logic.
Why: As programs grow larger, keeping all your code in a single file becomes unmanageable. Modules help you organize your project into separate, logical files, making the codebase cleaner, easier to maintain, and highly reusable.
Types of Modules
- Built-in Modules: Libraries that come pre-installed with Python (e.g.,
math,random,datetime,os). - User-defined Modules: Custom Python files (e.g.,
my_functions.py) that you create yourself and import into other files. - External Modules: Libraries created by the community that you can install using package managers like
pip(e.g.,requests,pandas).
Example (Using a Built-in Module)
import math
# Using a function from the imported math module
result = math.sqrt(25)
print(result) # Output: 5.0
Explanation
- The
importKeyword: This tells Python to load the specified module (in this case,math) into your current script. - Dot Notation: To access a function inside a module, you use the module name followed by a dot and the function name (
math.sqrt()). This specifies exactly where the function is coming from.
Alternative Ways to Import
Python offers flexible ways to bring module features into your workspace depending on your needs:
# 1. Importing specific functions directly (no need to use 'math.' prefix)
from math import sqrt
print(sqrt(16)) # Output: 4.0
# 2. Importing a module with an alias (renaming it for convenience)
import math as m
print(m.sqrt(9)) # Output: 3.0
Key Notes
- Any Python file you save with a
.pyextension can technically be imported as a module into another file located in the same directory. - It is standard practice to place all
importstatements at the very top of your Python file. - Importing only what you need (using the
from ... import ...syntax) can make your code slightly cleaner, but be careful not to accidentally overwrite functions with identical names.
Example
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute