Python Modules

In the last lesson you learned about Magic Methods, the special functions that let your own objects behave like built-in ones. Now we zoom out from single objects to whole files. As your programs grow you will want to split your code across many files. You will also want to reuse code that other people already wrote. That is exactly what a module gives you.

🤔 Why Modules?

Imagine you are building a project and you keep everything in one big file. At first it is fine. Then the file grows. Soon you are scrolling past hundreds of lines just to find one function. You copy a useful function into another project. Later you fix a bug in one copy and forget the other. It gets messy fast.

A module fixes this. A module is simply a .py file full of reusable code. You write the code once in its own file. Then you pull it into any other file that needs it. No copy-paste. No giant single file.

Here is the pain and the fix in one line:

  • The pain: one huge file is hard to read, hard to manage, and hard to reuse.
  • The fix: split related code into separate .py files (modules) and import what you need, where you need it.

📦 What Is a Module?

Think of a module like an app on your phone. You do not rebuild the camera every time you want a photo. You open the camera app and use it. A module works the same way. Someone wrote the code, packaged it in a file, and now you just open it and use the parts you need.

In Python the word “module” means one simple thing:

  • A module is a single .py file.
  • Inside it you have functions, variables, and classes ready to use.
  • Another file brings it in with the import keyword.

So math is a module. random is a module. The file you are writing right now is also a module. They are all just files of Python code.

🧮 Importing a Built-in Module

Python comes with a big set of ready-made modules called the standard library. These ship with Python, so you do not install anything. You just import and go.

Let’s start with the math module. It holds math helpers like square roots and the value of pi. This code imports it and finds the square root of 144.

import math
result = math.sqrt(144)
print(result)

Output

12.0

Here is what each line does:

  • import math brings the whole math module into your file.
  • math.sqrt(144) reaches into math and calls its sqrt function. The dot means “look inside math and use sqrt”.
  • print(result) shows the answer, which is 12.0.

The pattern is always the same. You write the module name, then a dot, then the thing you want from it. So math.sqrt reads as “the sqrt function that lives inside math”.

The math module carries more than square roots. Here we use math.pi for the value of pi and math.floor to round a number down.

import math
print(math.pi)
print(math.floor(7.8))

Output

3.141592653589793
7

Tip

You do not need to memorize what is inside math. The thing to remember is the shape: import the module, then use module.thing. Once you know that shape, every module works the same way.

🎲 Another Module: random

The random module helps when you want something unpredictable. Maybe you want to pick a random winner. Or shuffle a deck of cards. Or roll a die.

Say Alex runs a small giveaway and wants to pick one name from a list. The random.choice function picks one item at random.

import random
names = ["Riya", "Arjun", "Alex", "Sara"]
winner = random.choice(names)
print(f"The winner is {winner}!")

Output

The winner is Arjun!

Your output may show a different name each time you run it. That is the whole point of random. It does not give the same answer every time.

A quick walk through the code:

  • import random brings the module in.
  • random.choice(names) looks inside the list and grabs one item by chance.
  • The f-string drops that name into the sentence.

The random module has more tricks too. random.randint gives you a whole number in a range. That is handy for things like rolling a die.

import random
dice = random.randint(1, 6)
print(f"You rolled a {dice}")

Output

You rolled a 4

🗂️ The Standard Library Gives You a Lot for Free

The big win here is that Python already ships with modules for everyday jobs. You do not download them. You do not write them. You just import them. Here are a few you will meet often.

Module What it helps with
math Square roots, pi, rounding, powers
random Random picks, shuffling, random numbers
datetime Dates and times, like today’s date
os Files and folders on your computer
json Reading and writing JSON data

Think of the standard library like a toolbox that came with Python. The tools are already inside. You just reach for the one you need.

Note

The standard library is huge, far more than this table. When you have a common task, search “python standard library” plus what you want. There is a good chance a module already does it.

⚠️ Common Mistakes

A few small slips trip people up early on. Here is what to watch for.

You forget the module name before the dot. The function lives inside the module, so you must say where it lives.

import math
# ❌ Avoid: sqrt on its own is not defined
print(sqrt(144))
# ✅ Good: tell Python the function lives in math
print(math.sqrt(144))

If you run the wrong version you get an error. Python stops at the very first error. So only the NameError shows, and the good line below it never runs.

Output

NameError: name 'sqrt' is not defined

You misspell the module name. Python looks for a file or built-in module with that exact name, so a typo means it cannot find it.

# ❌ Avoid: "maths" is not a real module
import maths
# ✅ Good: the module is called math
import math

The wrong spelling gives this error.

Output

ModuleNotFoundError: No module named 'maths'

You put import in the middle of your file. It works, but it is hard to read. Keep imports at the top so anyone can see at a glance what your file depends on.

✅ Best Practices

Small habits keep your imports clean and easy to follow.

  • Put all your import lines at the very top of the file.
  • Import only the modules you actually use. Unused imports just add clutter.
  • Lean on the standard library before writing your own version. It is well tested and free.
  • Use the clear shape module.thing so readers can see where each function comes from.

🧩 What You’ve Learned

You now know what modules are and why they make your life easier.

  • ✅ A module is just a .py file full of reusable code.
  • ✅ Splitting code into modules beats stuffing everything into one giant file.
  • ✅ You bring a module in with import, then use it as module.thing.
  • math gives you helpers like math.sqrt and math.pi.
  • random gives you picks like random.choice and random.randint.
  • ✅ The standard library ships many modules for free, no install needed.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    What is a Python module, in simple terms?

    Why: A module is simply a .py file containing code (functions, variables, classes) you can reuse in other files.

  2. 2

    Which line correctly uses the sqrt function from the math module?

    Why: You write the module name, a dot, then the function: math.sqrt(144).

  3. 3

    What does the standard library mean?

    Why: The standard library is a large set of modules that come with Python, ready to import without installing anything.

  4. 4

    Why split code into modules instead of one big file?

    Why: Modules keep related code together so it is easier to read, manage, and reuse without copy-pasting.

🚀 What’s Next?

You have seen import in action, but it has a few more forms worth knowing. You can grab just one function from a module. You can also give a module a shorter name. That is exactly where we go next.

Import Statement

Share & Connect