MODULES IN PYTHON - EXPLAINED WITH EXAMPLES
1. What are Modules?
Modules in Python are like libraries - they are collections of code (functions, variables, classes) you
can reuse in your programs. Instead of writing code from scratch, you import modules to get things
done faster and cleaner.
Examples of common Python libraries/modules:
- math (mathematical operations)
- json (for reading and writing JSON data)
- random (to generate random numbers)
- cv2 (OpenCV for image processing)
- pandas (data manipulation)
2. Types of Modules
Modules are of two types:
- Built-in Modules (already available in Python, like `math`, `json`, `os`)
- User-defined Modules (custom modules you create, like `mymodule.py`)
Some examples by type:
- Mathematical Module: math, random
- Data Handling: json, pandas
- Image Processing: cv2 (OpenCV)
3. User-defined Module Example: mymodule.py
This module defines a dictionary called `person1`:
Example:
person1 = {
"name": "john",
"age": 25,
"country": "USA",
"hobby": "book"
You can use it by importing:
from mymodule import person1
print(person1["name"])
4. Built-in Module Example: json 2.py
- json.dumps(): Converts Python object to JSON string
- json.loads(): Parses JSON string into Python dict
This code also uses `set()` to remove duplicates from a list.
Examples:
- Convert string to JSON: json.dumps("hello")
- Parse JSON with fruits: ["apple", "orange"]
- Extract and print unique user names using `set()`
5. Function-based Module Example: fucntion.py
This module defines a function that:
1. Prints numbers 0 to 10
2. Prints numbers 10 to 0
3. Uses `break` to stop a loop after a condition
4. Accepts input to print multiplication table
5. Automatically prints 36's multiplication table
Key Concepts:
- while loop
- break statement
- input()
- f-strings