๐ข Lesson 6 โ Intermediate Level
๐ฐ What Is a Module?

A module is simply a Python file (.py
) containing code (functions, variables, classes) you can reuse in other programs.
Python has:
- Built-in modules (already included with Python, like
math
,random
,os
) - External libraries (installed with
pip
, likerequests
,pandas
) - Custom modules (your own
.py
files)
๐ฆ Importing a Module
pythonCopierModifierimport math
print(math.sqrt(25)) # Output: 5.0
๐ฏ Importing Specific Functions
pythonCopierModifierfrom math import sqrt, pi
print(sqrt(49)) # Output: 7.0
print(pi) # Output: 3.141592653589793
โ๏ธ Creating Your Own Module
- Create a file called mymodule.py:
pythonCopierModifierdef greet(name):
return f"Hello, {name}!"
pi_value = 3.1416
- In another Python file:
pythonCopierModifierimport mymodule
print(mymodule.greet("Ali"))
print(mymodule.pi_value)
๐ Installing External Libraries with pip
Example: Install and Use requests
- In your terminal or command prompt:
bashCopierModifierpip install requests
- In Python:
pythonCopierModifierimport requests
response = requests.get("https://api.github.com")
print(response.status_code)
๐ Popular Python Libraries
Library | Purpose |
---|---|
math | Mathematical functions |
random | Random number generation |
os | Interact with the operating system |
datetime | Dates and times |
requests | HTTP requests (APIs, web data) |
pandas | Data analysis |
numpy | Numerical computing |
๐ง Exercise 1: Using a Built-in Module
- Import the
random
module. - Generate 5 random integers between 1 and 50.
pythonCopierModifierimport random
for i in range(5):
print(random.randint(1, 50))
๐ง Exercise 2: Create and Import Your Module
- Create a module
calculator.py
with:add(a, b)
subtract(a, b)
- Import and use it in another script.
๐ Summary
- Modules let you reuse and organize your code.
- Use
import
to bring in Pythonโs built-in modules. - Use
pip install
to add external libraries. - You can write your own modules for personal or team projects.