Importing Modules
Use import to load a module. Access its contents with dot notation.
import math
import random
print(math.pi) # 3.141592653589793
print(math.sqrt(25)) # 5.0
print(random.randint(1, 10)) # Random number 1-10from β¦ import β Import Specific Names
Import only what you need. No module prefix required after.
from math import sqrt, pi, ceil
from random import choice, shuffle
print(sqrt(16)) # 4.0 β no "math." prefix needed
print(ceil(4.2)) # 5
fruits = ["apple", "banana", "cherry"]
shuffle(fruits)
print(choice(fruits))Aliasing with as
Give modules or names shorter aliases.
import numpy as np # Convention: np
import pandas as pd # Convention: pd
from datetime import datetime as dt
# Now use the alias
print(dt.now().year)Creating Your Own Module
Any .py file is a module. Create mymath.py then import it.
# mymath.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
PI = 3.14159
# --- in main.py ---
import mymath
print(mymath.add(3, 4)) # 7
print(mymath.PI) # 3.14159Essential Standard Library Modules
Python ships with a huge standard library. Key modules: os (file system), sys (interpreter), datetime (dates), json (JSON), re (regex), pathlib (paths), collections (specialised containers), itertools (iterators), functools (higher-order functions).
import os
import sys
from pathlib import Path
print(os.getcwd()) # Current directory
print(sys.version) # Python version
print(Path.home()) # Home directoryThe __name__ == "__main__" Guard
Prevents module-level code from running when the file is imported.
# utils.py
def helper():
return "I help!"
if __name__ == "__main__":
# This runs only when utils.py is run directly
# NOT when it is imported
print(helper())Always use this guard in scripts that also provide importable functions.