intermediateModules & Packages
Modules & Packages
Organize code with modules, imports, and packages.
In this lesson
01Importing Modules
Use import to access code from other files or built-in libraries.
Python
1import math2print(math.pi) # 3.1415926535897933print(math.sqrt(16)) # 4.045from datetime import datetime6now = datetime.now()7print(now.strftime("%Y-%m-%d %H:%M"))89import random as rng10print(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.py2def add(a, b):3 return a + b45def multiply(a, b):6 return a * b78if __name__ == "__main__":9 print("Running as script")10 print(add(2, 3))1112# main.py13from mymath import add, multiply14print(add(5, 3)) # 815print(multiply(4, 6)) # 24
Output
8 24