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
— step through the idea, then dive into the details below.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.
#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.
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".
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:
from math import sqrt, pi
print(sqrt(49))
print(pi)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).
import math as m
print(m.sqrt(16))
print(m.ceil(2.1))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 modulemain.py— your main program
# greetings.py
def hello(name):
return f"Hello, {name}!"
def goodbye(name):
return f"Goodbye, {name}. See you soon!"# 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:
# 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"))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
mathandrandom
You can see the full search path by printing sys.path:
import sys
for path in sys.path:
print(path)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.
What does this code print?
from math import sqrt, floor
print(sqrt(81))
print(floor(4.9))This code has a bug. What is wrong?
import math as m
print(math.sqrt(25))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))
Put these lines in the right order to define a module guard that only runs the print when the file is executed directly.
if __name__ == "__main__":
print(greet("Ada")) return f"Hi, {name}!"def greet(name):
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: