What if you didn’t have to write everything from scratch every time you code?
That’s exactly what modules help you do.
So far, we’ve learned how to write functions and even shorten them using lambda functions.
But as programs grow, keeping everything in one file becomes messy.
That’s where modules come in.
A module is simply a file that contains Python code functions, variables, or classes that you can reuse in other programs.
🔹 Using Built-in Modules
Python already comes with ready made modules.
For example, the math module:
import math
print(math.sqrt(16))
This calculates the square root of 16.
Instead of writing the logic yourself, you just use what already exists.
🔹 Importing Specific Features
Sometimes you don’t need the whole module just one part.
from math import sqrt
print(sqrt(25))
This imports only the square root function.
🔹 Creating Your Own Module
You can also create your own module.
Imagine you have a file called my_functions.py:
def greet(name):
return "Hello " + name
Now you can use it in another file:
import my_functions
print(my_functions.greet("Mary"))
🔹 Why Modules Matter
Modules help you:
- Organize your code
- Reuse functions easily
- Keep programs clean
- Work on bigger projects without confusion In real development, no one writes everything in one file. Modules make large systems manageable.
🌱 Challenge
- Import the
mathmodule - Use it to:
- Find the square root of 49
- Find the value of pi (
math.pi)
- Then create your own module with a function that:
- Takes a name
- Returns a greeting Try importing it into another file and using it.
Next, we’ll explore file handling, where your programs start working with real files like .txt just like real applications do.
Top comments (0)