DEV Community

still-purrfect
still-purrfect

Posted on

Modules in Programming: Using and Organizing Code Like a Pro

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))
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Now you can use it in another file:

import my_functions

print(my_functions.greet("Mary"))
Enter fullscreen mode Exit fullscreen mode

🔹 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

  1. Import the math module
  2. Use it to:
    • Find the square root of 49
    • Find the value of pi (math.pi)
  3. 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)