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!")
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.
26 examples, in lesson order.
# 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!")
# Stick a label called hero_level
# onto the integer 7
hero_level = 7
print(hero_level)
print(type(hero_level))
# 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__)
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)
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)
# 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}")
# Summoning the dragon boss
countdown = 5
while countdown > 0:
print(f"Dragon arrives in {countdown}...")
countdown = countdown - 1
print("The dragon roars to life!")
party = ["Cloud", "Tifa", "Aerith", "Barret"]
for hero in party:
print(f"{hero} joins the battle!")
command = ("attack", "dragon")
match command:
case ("attack", target):
print(f"Striking {target}!")
case ("heal",):
print("Restoring HP!")
case ("flee",):
print("Escaping the fight!")
# 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))
# 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])
# 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)
# 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!")
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))
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}")
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)
def loot_drops():
yield "Iron Sword"
yield "Health Potion"
yield "Dragon Scale"
bag = loot_drops()
print(next(bag))
print(next(bag))
print(next(bag))
# 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)
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()
# 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!")
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")
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)
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")
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}")
# 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}")
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)
The full course walks through every one of these examples on video, at your own pace, with quizzes and a verifiable certificate when you finish.