Importing Modules
Importing Modules
A module is useful when you can use its code in another file.
Python uses import for this.
What Does Import Mean?
Import means bringing code from another module into your program.
After importing, you can use functions, variables, or classes from that module.
Basic Import
import math
Now you can use the math module.
Example: square root
import math
print(math.sqrt(25))
Output
5.0
Import Your Own Module
If you created:
tools.py
With:
def hello():
print("Hello")
Use it in another file:
import tools
tools.hello()
Output
Hello
Import Specific Item
Use from ... import ...
from math import sqrt
print(sqrt(16))
Output
4.0
Now you do not need math. before sqrt.
Import Multiple Items
from math import sqrt, pi
print(sqrt(9))
print(pi)
Output
3.0
3.141592653589793
Use an Alias
An alias is a shorter name.
import math as m
print(m.sqrt(36))
Output
6.0
Why Use Aliases?
Helpful when names are long.
Example:
import pandas as pd
Common Beginner Errors
Wrong File Name
The module name must match the file name.
File Not in Same Folder
Your file should be in the same project folder (for now).
Misspelled Function Name
Check spelling carefully.
Code Along
Import random.
Use:
random.randint(1, 10)
Mini Challenge
Create:
numbers.py
Add:
def triple(n):
return n * 3
Import it and print:
15
Real World Use Case
Projects import modules for math, files, APIs, data tools, web apps, and reusable code.
Quiz
- What does
importdo? - What is the difference between
import mathandfrom math import sqrt? - What is an alias?
- Why do we import modules?
Assignment
Create your own module with one function and import it using an alias.
Summary
You learned how to import modules, import specific items, and use aliases in Python.