What’s one thing you learned? What’s still confusing?
Environment Variables & Secrets: Never Hardcode API Keys
Keep API keys out of code using os.environ, .env files, and python-dotenv.
Calling APIs in Python: requests, JSON & Authentication
Master the requests library — GET/POST, JSON parsing, API auth, error handling.
The collections Module
Counter, defaultdict, OrderedDict, namedtuple, deque, plus heapq and bisect.
Interactive Labs for This Track
Loop Visualizer
You're a factory robot repeating the same task on an assembly line — watch how loops automate repetitive work
List Slicing
You have a playlist of 50 songs — grab just tracks 10 through 20 with a single slice expression
Sorting Algorithms
You're organizing a library of 10,000 books — which sorting method is fastest?
Ask questions, share insights
__init__.py is how you graduate from "scripts in one file" to building software other people can install with one command..py file containing Python code. When you import it, you get access to its functions, classes, and variables.# Importing entire modules
import math
import random
import os
import datetime
# Using module functions with module_name.function_name
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
print(random.randint(1, 6)) # random number 1-6 (like a dice roll)
print(os.getcwd()) # current working directory
# Getting today's date
today = datetime.date.today()
print(f"Today: {today}")There are several ways to import:
# Method 1: Import the whole module
import math
print(math.sqrt(16)) # must use math.sqrt()
# Method 2: Import specific items
from math import sqrt, pi
print(sqrt(16)) # can use sqrt() directly
print(pi) # 3.14159...
# Method 3: Import with an alias (nickname)
import numpy as np # convention everyone follows
import pandas as pd # convention everyone follows
import matplotlib.pyplot as plt # convention everyone follows
# Method 4: Import everything (AVOID this)
# from math import * # BAD -- pollutes namespace, causes name conflictsEvery AI tutorial and codebase uses the same aliases. They are not optional conventions -- they are industry standards:
import numpy as np # numerical computing
import pandas as pd # data manipulation
import matplotlib.pyplot as plt # plotting
import seaborn as sns # statistical visualization
import tensorflow as tf # deep learning
import torch # PyTorch (no alias needed, already short)
from sklearn.model_selection import train_test_split # specific importnp.array() in a tutorial, you know it means NumPy. When you see pd.DataFrame(), you know it means Pandas. These aliases are universal.HitModuleNotFoundErrororImportError?ModuleNotFoundError: No module named 'numpy'means the package isn't installed in your current environment (pip install numpy);ImportError: cannot import name 'X' from 'pkg'means the symbol moved or you typo'd. See the error decoder for the full fix flow.
.py file is a module. Here is how you create and use one:# File: math_helpers.py
"""Custom math utility functions."""
PI = 3.14159265358979
def circle_area(radius):
"""Calculate the area of a circle."""
return PI * radius ** 2
def circle_circumference(radius):
"""Calculate the circumference of a circle."""
return 2 * PI * radius
def celsius_to_fahrenheit(celsius):
"""Convert Celsius to Fahrenheit."""
return celsius * 9 / 5 + 32
def fahrenheit_to_celsius(fahrenheit):
"""Convert Fahrenheit to Celsius."""
return (fahrenheit - 32) * 5 / 9# File: main.py (in the same directory)
import math_helpers
area = math_helpers.circle_area(5)
print(f"Area: {area:.2f}") # Area: 78.54
temp_f = math_helpers.celsius_to_fahrenheit(100)
print(f"100C = {temp_f}F") # 100C = 212.0F
# Or import specific functions
from math_helpers import circle_area, celsius_to_fahrenheit
print(circle_area(10)) # 314.16
print(celsius_to_fahrenheit(37)) # 98.6__name__ Guard__name__ to "__main__". When the file is imported as a module, __name__ is set to the module's name:# File: math_helpers.py
def circle_area(radius):
return 3.14159 * radius ** 2
# This block ONLY runs when the file is executed directly
# It does NOT run when the file is imported
if __name__ == "__main__":
# Test code -- great for quick testing
print("Running tests...")
print(f"Area of r=5: {circle_area(5):.2f}")
print(f"Area of r=10: {circle_area(10):.2f}")
print("All tests passed!")$ python math_helpers.py # __name__ == "__main__" --> tests run
Running tests...
Area of r=5: 78.54
Area of r=10: 314.16
All tests passed!
$ python main.py # math_helpers imported --> tests do NOT run
When you 'import math_helpers' in main.py, does the if __name__ == '__main__' block in math_helpers.py run?
__name__ is "math_helpers", not "__main__", so the guard block is skipped. This is why you see if __name__ == "__main__": in almost every Python script.__init__.py file:ML Project Package Structure
# In main.py, you can import from packages:
from data.loader import load_csv
from data.preprocessor import normalize
from models.neural import NeuralNetwork
from utils.metrics import accuracy, f1_score
# Or import the package and use dot notation
import models.linear
model = models.linear.LinearRegression()__init__.py file can be empty (just marks the directory as a package) or can contain initialization code and convenience imports.# Install a package
pip install numpy
# Install a specific version
pip install numpy==1.26.4
# Install multiple packages
pip install numpy pandas matplotlib scikit-learn
# Upgrade a package
pip install --upgrade numpy
# Uninstall a package
pip uninstall numpy
# See what is installed
pip list
# Show details about a package
pip show numpy
# Create a virtual environment
python -m venv myproject_env
# Activate it (Mac/Linux)
source myproject_env/bin/activate
# Activate it (Windows)
myproject_env\Scripts\activate
# Now pip installs into THIS environment only
pip install numpy pandas matplotlib
# See what is installed in this environment
pip list
# Deactivate when done
deactivate
requirements.txt file lists all packages a project needs, making it reproducible:# Generate requirements.txt from current environment
pip freeze > requirements.txt
# Install everything from requirements.txt
pip install -r requirements.txt
requirements.txt:numpy==1.26.4
pandas==2.2.0
matplotlib==3.8.2
scikit-learn==1.4.0
torch==2.2.0
Python's standard library is extensive. Here are modules you will use constantly:
# os -- file system operations
import os
print(os.listdir(".")) # list files in current directory
print(os.path.exists("data.csv")) # check if file exists
os.makedirs("output/plots", exist_ok=True) # create nested directories
# pathlib -- modern file paths (recommended over os.path)
from pathlib import Path
data_dir = Path("data")
csv_files = list(data_dir.glob("*.csv")) # find all CSV files
# collections -- specialized data structures
from collections import Counter, defaultdict
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
print(Counter(words)) # Counter({'apple': 3, 'banana': 2, 'cherry': 1})
# itertools -- efficient iteration tools
from itertools import combinations, product
print(list(combinations([1, 2, 3], 2))) # [(1,2), (1,3), (2,3)]
# time -- timing operations
import time
start = time.time()
# ... do something ...
elapsed = time.time() - start
print(f"Took {elapsed:.3f} seconds")
# copy -- deep vs shallow copy
import copy
original = [[1, 2], [3, 4]]
shallow = original.copy() # nested lists are still shared
deep = copy.deepcopy(original) # completely independent copyTests · Build modules, import from them, and test that each function works correctly!
Interactive Lab
See how importing modules changes what's available in your namespace — and trace import errors step by step
import module gives you access to a module's contents -- use module.function() to call its functions. Use from module import function for direct access without the prefiximport numpy as np, import pandas as pd, import matplotlib.pyplot as plt. Every tutorial, blog post, and codebase uses themif __name__ == "__main__": guards script-only code -- put tests and demos inside this block so they run when executed directly but not when imported as a modulepython -m venv .venv for every project. This prevents version conflicts between projectsrequirements.txt makes projects reproducible -- pip freeze > requirements.txt saves your exact versions, pip install -r requirements.txt recreates the environment. Always include it in your repoWhat is the correct way to import NumPy with its standard alias?