Python Lesson Plan
A progressive curriculum to master Python through hands-on practice.
Lesson 1: First Steps
Section titled “Lesson 1: First Steps”Goal: Run Python and understand basic types.
Concepts
Section titled “Concepts”Python is dynamically typed and emphasizes readability. Indentation matters.
Exercises
Section titled “Exercises”-
Run Python interactively
Terminal window python3>>> 2 + 24>>> print("Hello, World!")Hello, World!>>> exit() -
Create and run a script
hello.py name = "Python"print(f"Hello, {name}!")Terminal window python3 hello.py -
Explore basic types
# Numbersx = 42 # inty = 3.14 # floatz = 1 + 2j # complex# Stringss = "hello"s.upper() # 'HELLO'len(s) # 5# Booleansflag = Truenot flag # False -
Type checking
type(42) # <class 'int'>type("hello") # <class 'str'>isinstance(42, int) # True
Checkpoint
Section titled “Checkpoint”Write a script that prints your name and age using f-strings.
Lesson 2: Collections
Section titled “Lesson 2: Collections”Goal: Work with lists, dicts, sets, and tuples.
Exercises
Section titled “Exercises”-
Lists (ordered, mutable)
nums = [1, 2, 3]nums.append(4) # [1, 2, 3, 4]nums.insert(0, 0) # [0, 1, 2, 3, 4]nums.pop() # 4, list is now [0, 1, 2, 3]nums[1:3] # [1, 2] (slicing)nums[-1] # 3 (last element) -
Dictionaries (key-value)
user = {"name": "Alice", "age": 30}user["name"] # "Alice"user.get("email", "N/A") # "N/A" (default)user["email"] = "a@b.com""name" in user # Truefor key, value in user.items():print(f"{key}: {value}") -
Sets (unique, unordered)
a = {1, 2, 3}b = {2, 3, 4}a | b # {1, 2, 3, 4} uniona & b # {2, 3} intersectiona - b # {1} difference -
Tuples (immutable)
point = (3, 4)x, y = point # Unpackingpoint[0] # 3# point[0] = 5 # Error! Tuples are immutable
Checkpoint
Section titled “Checkpoint”Create a dict of 3 people with names and ages. Print each person’s info.
Lesson 3: Control Flow
Section titled “Lesson 3: Control Flow”Goal: Use conditionals, loops, and comprehensions.
Exercises
Section titled “Exercises”-
Conditionals
x = 10if x > 0:print("positive")elif x < 0:print("negative")else:print("zero")# Ternaryresult = "even" if x % 2 == 0 else "odd" -
Loops
# For loopfor i in range(5): # 0, 1, 2, 3, 4print(i)for item in ["a", "b", "c"]:print(item)for i, item in enumerate(["a", "b", "c"]):print(f"{i}: {item}")# While loopn = 0while n < 5:print(n)n += 1 -
List comprehensions
# Basicsquares = [x**2 for x in range(10)]# With filterevens = [x for x in range(10) if x % 2 == 0]# Dict comprehensionsquare_map = {x: x**2 for x in range(5)}# Set comprehensionunique_lengths = {len(word) for word in ["a", "bb", "ccc"]} -
Loop control
for i in range(10):if i == 3:continue # Skip this iterationif i == 7:break # Exit loopprint(i)
Checkpoint
Section titled “Checkpoint”Use a list comprehension to create a list of squares of even numbers from 1-20.
Lesson 4: Functions
Section titled “Lesson 4: Functions”Goal: Define and use functions effectively.
Exercises
Section titled “Exercises”-
Basic functions
def greet(name):"""Return a greeting string."""return f"Hello, {name}!"greet("Alice") # "Hello, Alice!" -
Default and keyword arguments
def greet(name, greeting="Hello"):return f"{greeting}, {name}!"greet("Bob") # "Hello, Bob!"greet("Bob", greeting="Hi") # "Hi, Bob!" -
*args and **kwargs
def sum_all(*args):return sum(args)sum_all(1, 2, 3, 4) # 10def print_info(**kwargs):for key, value in kwargs.items():print(f"{key}: {value}")print_info(name="Alice", age=30) -
Lambda functions
double = lambda x: x * 2double(5) # 10# Common with sorted, map, filternames = ["Alice", "Bob", "Charlie"]sorted(names, key=lambda x: len(x))# ['Bob', 'Alice', 'Charlie']
Checkpoint
Section titled “Checkpoint”Write a function that takes a list of numbers and returns only the positive ones.
Lesson 5: Classes
Section titled “Lesson 5: Classes”Goal: Define classes and understand OOP basics.
Exercises
Section titled “Exercises”-
Basic class
class Dog:def __init__(self, name, age):self.name = nameself.age = agedef bark(self):return f"{self.name} says woof!"dog = Dog("Rex", 3)dog.bark() # "Rex says woof!" -
Class methods and properties
class Circle:def __init__(self, radius):self._radius = radius@propertydef radius(self):return self._radius@radius.setterdef radius(self, value):if value < 0:raise ValueError("Radius must be positive")self._radius = value@propertydef area(self):return 3.14159 * self._radius ** 2 -
Inheritance
class Animal:def __init__(self, name):self.name = namedef speak(self):raise NotImplementedErrorclass Cat(Animal):def speak(self):return f"{self.name} says meow!" -
Dataclasses (Python 3.7+)
from dataclasses import dataclass@dataclassclass Point:x: floaty: floatdef distance_from_origin(self):return (self.x**2 + self.y**2) ** 0.5p = Point(3, 4)p.distance_from_origin() # 5.0
Checkpoint
Section titled “Checkpoint”Create a BankAccount class with deposit, withdraw, and balance methods.
Lesson 6: Error Handling
Section titled “Lesson 6: Error Handling”Goal: Handle exceptions gracefully.
Exercises
Section titled “Exercises”-
Try/except
try:result = 10 / 0except ZeroDivisionError:print("Cannot divide by zero") -
Multiple exceptions
try:value = int("abc")except ValueError:print("Invalid integer")except TypeError:print("Wrong type")except Exception as e:print(f"Unexpected error: {e}") -
Finally and else
try:f = open("file.txt")data = f.read()except FileNotFoundError:print("File not found")else:print("File read successfully")finally:print("Cleanup here") -
Raising exceptions
def divide(a, b):if b == 0:raise ValueError("Divisor cannot be zero")return a / b# Custom exceptionsclass ValidationError(Exception):pass
Checkpoint
Section titled “Checkpoint”Write a function that reads a file and handles FileNotFoundError gracefully.
Lesson 7: Modules and Packages
Section titled “Lesson 7: Modules and Packages”Goal: Organize code into modules.
Exercises
Section titled “Exercises”-
Import modules
import mathmath.sqrt(16) # 4.0from math import sqrt, pisqrt(16) # 4.0from math import sqrt as square_rootsquare_root(16) # 4.0 -
Create a module
mymodule.py def greet(name):return f"Hello, {name}!"PI = 3.14159# main.pyfrom mymodule import greet, PI -
Package structure
mypackage/├── __init__.py├── utils.py└── models/├── __init__.py└── user.pyfrom mypackage.utils import helperfrom mypackage.models.user import User -
Virtual environments
Terminal window python3 -m venv venvsource venv/bin/activate # Unixvenv\Scriptsctivate # Windowspip install requestspip freeze > requirements.txt
Checkpoint
Section titled “Checkpoint”Create a package with two modules. Import functions from both in a main script.
Lesson 8: Modern Python
Section titled “Lesson 8: Modern Python”Goal: Use type hints, context managers, and generators.
Exercises
Section titled “Exercises”-
Type hints
def greet(name: str) -> str:return f"Hello, {name}!"from typing import List, Dict, Optionaldef process(items: List[int]) -> Dict[str, int]:return {"sum": sum(items), "count": len(items)}def find_user(id: int) -> Optional[str]:return None # or a string -
Context managers
# Using with statementwith open("file.txt", "w") as f:f.write("Hello")# Custom context managerfrom contextlib import contextmanager@contextmanagerdef timer():import timestart = time.time()yieldprint(f"Elapsed: {time.time() - start:.2f}s")with timer():# do workpass -
Generators
def count_up(n):i = 0while i < n:yield ii += 1for num in count_up(5):print(num)# Generator expressionsquares = (x**2 for x in range(1000000)) # Lazy evaluation -
Async/await
import asyncioasync def fetch_data(url):await asyncio.sleep(1) # Simulate networkreturn f"Data from {url}"async def main():results = await asyncio.gather(fetch_data("url1"),fetch_data("url2"),)print(results)asyncio.run(main())
Checkpoint
Section titled “Checkpoint”Write a generator that yields Fibonacci numbers. Use type hints.
Practice Projects
Section titled “Practice Projects”Project 1: CLI Tool
Section titled “Project 1: CLI Tool”Build a command-line todo list:
- Add, remove, list tasks
- Save to JSON file
- Use argparse for commands
Project 2: Web Scraper
Section titled “Project 2: Web Scraper”Scrape a website:
- Use requests and BeautifulSoup
- Handle errors gracefully
- Save results to CSV
Project 3: REST API
Section titled “Project 3: REST API”Build a simple API with FastAPI:
- CRUD operations
- Type hints and validation
- Async endpoints
Quick Reference
Section titled “Quick Reference”| Stage | Topics |
|---|---|
| Beginner | Types, collections, control flow, functions |
| Intermediate | Classes, exceptions, modules, file I/O |
| Advanced | Type hints, generators, async, decorators |
See Also
Section titled “See Also”- Python Cheatsheet — Quick syntax reference
- Testing — pytest patterns
- Concurrency