Free learning resource

Source code & resources

Every code example from Python from First Principles to Pythonic Mastery — free to read, copy and run. No sign-up, no catch. If you found this from one of my courses, welcome; take the code and keep building.

Source code

Code from every lesson

26 examples, in lesson order.

1. Hello Python and the print Function Python

# Greet a brave hero
print("Welcome, brave hero!")

# Announce a treasure find
print("You found a golden chest!")

# Reveal the contents
print("Inside: 100 gold coins!")

2. Variables, Names, and Dynamic Typing Python

# Stick a label called hero_level
# onto the integer 7
hero_level = 7

print(hero_level)
print(type(hero_level))

3. Numbers, Strings, and Booleans Python

# Calculate the dragon's hoard
# It doubles every century
base_gold = 2
centuries = 100

dragon_hoard = base_gold ** centuries

print("Dragon hoard total:")
print(dragon_hoard)
print("Type:", type(dragon_hoard).__name__)

4. Operators and Expressions Python

base_damage = 50
crit_bonus = 25
spell_levels = 3

total_damage = base_damage + crit_bonus
combo_damage = total_damage * spell_levels
leftover = combo_damage - 75

print("Base hit total:", total_damage)
print("Combo damage:", combo_damage)
print("After enemy block:", leftover)

5. f-Strings and String Formatting Python

hero = "Cloud"
hero_hp = 87
mana = 42

# Drop variables straight into the string
status = f"{hero} has {hero_hp} HP and {mana} MP."
print(status)

# Expressions also work inside the braces
total = f"Total power: {hero_hp + mana}."
print(total)

6. if, elif, and else Python

# Set up our hero
hero_hp = 42

# Check if healing is needed
if hero_hp < 50:
    print("Hero needs healing!")
else:
    print("Hero is at full strength.")

print(f"Current HP: {hero_hp}")

7. while Loops and the Loop Else Python

# Summoning the dragon boss
countdown = 5

while countdown > 0:
    print(f"Dragon arrives in {countdown}...")
    countdown = countdown - 1

print("The dragon roars to life!")

8. for Loops and the range Object Python

party = ["Cloud", "Tifa", "Aerith", "Barret"]

for hero in party:
    print(f"{hero} joins the battle!")

9. match Statements for Structural Patterns Python

command = ("attack", "dragon")

match command:
    case ("attack", target):
        print(f"Striking {target}!")
    case ("heal",):
        print("Restoring HP!")
    case ("flee",):
        print("Escaping the fight!")

10. Truthiness, None, and Sentinel Values Python

# Common falsy values in Python
falsy = [0, "", [], {}, None]
for v in falsy:
    print(repr(v), "becomes", bool(v))

print()

# Common truthy values
truthy = [1, "hero", [0], -1]
for v in truthy:
    print(repr(v), "becomes", bool(v))

11. Lists and Slicing Python

# Build a loot inventory list
loot = ["Sword", "Shield", "Potion"]
print(loot)

# Check how many items we have
print(len(loot))

# Access individual loot items
print(loot[0])
print(loot[1])

# Use negative index from the end
print(loot[-1])

12. Tuples, Unpacking, and Immutability Python

# Lock our hero's stats into one tuple
hero_stats = (99, 87, 142)
print("Party leader stats locked in!")
print(hero_stats)
print(type(hero_stats))

# Tuples can mix types freely
boss_data = ("Dragon King", 9999, True)
print(boss_data)

13. Dictionaries as the Universal Map Python

# Build the wizard's spell book
spellbook = {
    "Fireball": 45,
    "Ice Lance": 30,
    "Lightning": 60,
    "Heal": 25,
}

# See the whole collection
print("Spell book contents:")
print(spellbook)

# Look up a single spell
damage = spellbook["Fireball"]
print(f"Fireball deals {damage} damage!")

14. Sets and Set Operations Python

loot_drops = [
    "potion", "sword", "potion",
    "shield", "sword", "gem",
    "potion", "gem"
]

unique_loot = set(loot_drops)
print("Original drops:")
print(loot_drops)
print("Unique loot items:")
print(unique_loot)
print("Total unique:", len(unique_loot))

15. Functions, Arguments, and Defaults Python

def deal_damage(attacker, target, amount):
    print(f"{attacker} strikes {target}!")
    print(f"{target} loses {amount} HP.")
    return amount

hit = deal_damage("Link", "Ganon", 75)
print(f"Total damage dealt: {hit}")

16. Comprehensions Replace Explicit Loops Python

spell_ranks = [1, 2, 3, 4, 5]

# Old way using an explicit for loop
spell_damage = []
for rank in spell_ranks:
    spell_damage.append(rank * rank)

print("Damage by rank:")
print(spell_damage)

# Cleaner one liner with a comprehension
quick_damage = [r * r for r in spell_ranks]
print("Comprehension result:")
print(quick_damage)

17. Generators and Lazy Iteration Python

def loot_drops():
    yield "Iron Sword"
    yield "Health Potion"
    yield "Dragon Scale"

bag = loot_drops()
print(next(bag))
print(next(bag))
print(next(bag))

18. map, filter, reduce, and Higher-Order Functions Python

# Spell base damage values
base_damage = [12, 25, 8, 40, 17]

# Power up each spell with a crit multiplier
crit_hits = list(map(lambda d: d * 3, base_damage))

# Compare both sets side by side
print("Base damage:", base_damage)
print("Crit damage:", crit_hits)

19. Decorators in Practice Python

def add_flame_aura(attack):
    def wrapped():
        print("Flames erupt!")
        attack()
        print("Embers fade.")
    return wrapped

def hero_attack():
    print("Hero swings the sword!")

flaming_attack = add_flame_aura(hero_attack)
flaming_attack()

20. Context Managers and the with Statement Python

# Write our quest list to a scroll
with open("quest_log.txt", "w") as scroll:
    scroll.write("Defeat the Ice Dragon\n")
    scroll.write("Find the Crystal Key\n")

# Read the scroll back, one line at a time
with open("quest_log.txt", "r") as scroll:
    for line in scroll:
        print(line.strip())

print("Scroll closed safely!")

21. Threads and Thread Pools for IO Work Python

import time

def fetch_loot_drop(boss_name):
    # Simulate a slow network call
    time.sleep(1)
    return f"{boss_name} dropped Legendary!"

bosses = ["Ifrit", "Bahamut", "Shiva", "Odin"]

start = time.perf_counter()
results = [fetch_loot_drop(b) for b in bosses]
elapsed = time.perf_counter() - start

for drop in results:
    print(drop)
print(f"Sequential time: {elapsed:.2f}s")

22. asyncio and the async/await Model Python

import asyncio

async def cast_spell():
    print("Casting fireball...")
    await asyncio.sleep(1)
    print("Fireball lands! 50 damage")

coro = cast_spell()
print(type(coro).__name__)
asyncio.run(coro)

23. multiprocessing for CPU-Bound Work Python

import time

def is_prime(n):
    if n < 2:
        return False
    limit = int(n**0.5) + 1
    for i in range(2, limit):
        if n % i == 0:
            return False
    return True

hoard = range(10_000_000, 10_001_000)

start = time.perf_counter()
gems = [n for n in hoard if is_prime(n)]
elapsed = time.perf_counter() - start

print(f"Found {len(gems)} prime gems")
print(f"Sequential time: {elapsed:.2f}s")

24. Dataclasses, Type Hints, and Generics Python

from dataclasses import dataclass

@dataclass
class Hero:
    name: str
    level: int
    hp: int

link = Hero("Link", 12, 240)
print(link)
print(f"{link.name} hit level {link.level}")

25. Errors, exceptions, and the EAFP Style Python

# Try to grab loot from a chest
loot_pile = ["potion", "gold", "rune"]

try:
    prize = loot_pile[10]
    print("You got " + prize)
except IndexError as err:
    print("Empty slot!")
    print(f"Reason: {err}")

26. Data Visualization with Matplotlib and pandas Python

import pandas as pd

# Boss raid damage log
raid_data = {
    "hero": ["Cloud", "Aerith", "Tifa",
             "Yuffie", "Vincent", "Barret"],
    "class": ["Warrior", "Mage", "Warrior",
              "Rogue", "Mage", "Warrior"],
    "damage": [4200, 5100, 3800,
               2900, 5600, 4500],
}

party = pd.DataFrame(raid_data)
print(party)