intermediateModules & Packages

Modules & Packages

Organize code with modules, imports, and packages.

01Importing Modules

Use import to access code from other files or built-in libraries.

Python
1import math
2print(math.pi) # 3.141592653589793
3print(math.sqrt(16)) # 4.0
4
5from datetime import datetime
6now = datetime.now()
7print(now.strftime("%Y-%m-%d %H:%M"))
8
9import random as rng
10print(rng.randint(1, 100))
Output
3.141592653589793
4.0
2026-06-08 21:00
42

02Creating Your Own Module

Any .py file can be imported as a module. Use if __name__ == "__main__" to make it runnable standalone.

Python
1# mymath.py
2def add(a, b):
3 return a + b
4
5def multiply(a, b):
6 return a * b
7
8if __name__ == "__main__":
9 print("Running as script")
10 print(add(2, 3))
11
12# main.py
13from mymath import add, multiply
14print(add(5, 3)) # 8
15print(multiply(4, 6)) # 24
Output
8
24