Modules & PackagesBeginner8 min45 / 63

Modules & import

Learn how to use Python's built-in modules, import exactly what you need, create your own reusable module, and understand the special __name__ guard.

Imagine you are baking a cake. You do not grow your own wheat or churn your own butter — you grab ingredients from the pantry. Python modules work the same way. A module is a file of ready-made code you can pull into your program so you do not have to write everything from scratch. Python ships with a huge pantry of modules called the standard library, and you can also create your own.

See it in action

Visual walkthrough1 / 6
1

Don't Reinvent the Wheel

A module is a ready-made .py file full of useful code. Instead of writing everything yourself, you import it and put it straight to work.

Python ships with hundreds of built-in modules — they're called the standard library.

#What is a module?

A module is simply a `.py` file that contains functions, variables, or classes. When you import it, Python runs that file and makes everything inside available to you. That is all there is to it — no magic involved.

Think of it like

The toolbox analogy

Think of a module as a toolbox. The math module is a toolbox full of mathematical tools. You import the toolbox once, then reach in and grab any tool you need — math.sqrt, math.pi, math.floor, and so on.

#import math

The simplest way to use a module is to import it by name. After that you access its contents using a dot — like math.sqrt(25). The dot is like saying "from the math toolbox, give me sqrt".

Importing the whole math module and using a few of its tools
import math

result = math.sqrt(25)
print(result)

print(math.pi)
print(math.floor(3.9))

#from ... import — grab just what you need

Sometimes you only need one or two tools from a module. You can import them directly so you do not have to type the module name every time. Use the from ... import form:

Importing sqrt and pi directly — no 'math.' prefix needed
from math import sqrt, pi

print(sqrt(49))
print(pi)
Tip

Which style should you use?

Use import math (the whole module) when you use many things from it. Use from math import sqrt when you only need one or two specific things. Both are perfectly fine — it is a style choice.

#import ... as — giving a module a nickname

Sometimes a module name is long or clashes with a name you already have. You can give it a short alias using as. This is very common with popular libraries like numpy (aliased as np) or pandas (aliased as pd).

Using 'as' to create a shorter alias for math
import math as m

print(m.sqrt(16))
print(m.ceil(2.1))
Common mistake

Do not overwrite built-in names

Avoid naming your own variables or files after built-in modules. If you create a file called math.py in your project, Python will import your file instead of the real math module, causing confusing errors. The same goes for names like random.py, os.py, or json.py.

#Creating your own module

Any .py file you write is a module. Put reusable functions in one file, then import them into another. Here is a tiny example. Suppose you have two files side by side:

  • greetings.py — your custom module
  • main.py — your main program
greetings.py — a simple module with two functions
# greetings.py

def hello(name):
    return f"Hello, {name}!"

def goodbye(name):
    return f"Goodbye, {name}. See you soon!"
main.py — importing and using the greetings module
# main.py

import greetings

print(greetings.hello("Alice"))
print(greetings.goodbye("Bob"))

#The if __name__ == "__main__" guard

Here is something that trips up almost every beginner. When Python imports a module, it runs all the code at the top level of that file. If your module has test prints or function calls at the top level, they will run every time someone imports it — which is almost never what you want.

The fix is a special guard:

The guard keeps test code from running on import
# greetings.py

def hello(name):
    return f"Hello, {name}!"

if __name__ == "__main__":
    # This only runs when you execute this file directly.
    # It does NOT run when someone imports greetings.
    print(hello("World"))
Note

How does __name__ work?

Every Python file has a built-in variable called __name__. When you run a file directly (python greetings.py), Python sets __name__ to the string "__main__". When a file is imported, __name__ is set to the module's filename (e.g. "greetings"). The guard checks which situation you are in.

#Where does Python look for modules?

When you write import greetings, Python searches for it in this order:

  • Your current directory — the folder where your script lives
  • Installed packages — things you installed with pip
  • The standard library — Python's built-in modules like math and random

You can see the full search path by printing sys.path:

sys.path shows where Python searches for modules (output varies by system)
import sys

for path in sys.path:
    print(path)
Quick check

You have a file called utils.py with a function called add(). Which line correctly imports ONLY the add function so you can call it as add(2, 3)?

Key takeaways

  • A module is just a .py file — any file you write is automatically a module.
  • Use `import math` to import a whole module, or `from math import sqrt` to grab one specific item.
  • Give long module names a short alias with `import numpy as np`.
  • Wrap code you only want to run directly (not on import) in an `if __name__ == "__main__":` guard.
  • Python searches your current folder first, then installed packages, then the standard library.
Practice challenges
Test yourself · earn XP
0/4
Predict the output#1

What does this code print?

predict-output
from math import sqrt, floor

print(sqrt(81))
print(floor(4.9))
Fix the bug#2

This code has a bug. What is wrong?

fix-bug
import math as m

print(math.sqrt(25))
Fill in the blank#3

Complete the code so it imports only the 'ceil' function from math and prints the result of rounding 3.2 up.

from math  ceil

print(ceil(3.2))
Reorder the lines#4

Put these lines in the right order to define a module guard that only runs the print when the file is executed directly.

1
if __name__ == "__main__":
2
    print(greet("Ada"))
3
    return f"Hi, {name}!"
4
def greet(name):
Your turn
Practice exercise

Create a module called calculator.py that contains four functions: add(a, b), subtract(a, b), multiply(a, b), and divide(a, b). The divide function should return the string 'Cannot divide by zero' if b is 0. Add an if __name__ == '__main__': block that tests each function and prints the results. Then, in a separate file main.py, import only add and multiply from calculator and print their results.

Try it live — edit the code and hit Run to execute real Python:

solution.py · editable