π§ͺ Code Examples
in Python
Runnable Python code examples by topic: strings, lists, dictionaries, functions, files, classes, errors and more, with links to full lessons.
What this lesson is about
Reading about code only takes you so far. You learn Python fastest by running small examples, changing them and watching what happens. This page is a collection of short examples grouped by topic. Each one runs in your browser, prints a result and is followed by a line-by-line explanation.
Treat it as a workshop, not a book. Pick a topic, press Run, then edit one thing and run it again. Change a number, rename a variable, break the code on purpose and read the error. That loop of predict, run and compare is how programming skill is actually built.
At the end of each section I link to the full lessons and projects on Poetic Bytes where the topic is covered in depth, so this page also works as a map of the site. Start anywhere and follow the links when you want more.
What you will learn
- βCore text, list and dictionary patterns you will use daily
- βHow to write and test small functions
- βReading and writing files safely
- βClasses and dataclasses in a few lines
- βHandling errors without crashing
- βUseful standard library helpers
- βHow to practise with predict, run and compare
- βWhere to go next on Poetic Bytes
Why programmers should learn this
- β Short examples are the fastest way to see how a feature behaves.
- β A library of patterns you recognise makes new problems feel familiar.
- β Running and changing code builds the habit of experimenting instead of memorising.
- β Examples grouped by topic work as a quick reference when you forget a detail.
- β Links to full lessons give you a clear next step instead of a dead end.
Text and strings
Strings are the first thing most programs touch. The tools below handle most everyday jobs: cleaning whitespace, changing case, splitting text into words, joining it back and checking what a string starts or ends with. They return new strings and never change the original, because strings in Python are immutable.
Format strings, written with an f before the quote, put values straight into text. You can control the width, the number of decimals and the alignment inside the braces. Learn them once and you will use them in every program you write.
Try changing the sentence to your own text and see how each result responds. For a deeper walk through, see the strings lesson.
A good way to use this section is to treat each line as a question. What does strip leave behind? What would split do with commas instead of spaces? Answer from memory, run the code and check. You will remember an answer you predicted far longer than one you simply read.
text = " Poetic Bytes teaches Python for free "
clean = text.strip()
words = clean.split()
print(clean)
print(len(words), "words")
print(clean.upper())
print("-".join(w.lower() for w in words))
print(clean.startswith("Poetic"), clean.endswith("!"))
print(clean.replace("free", "everyone"))
price, units = 2.5, 12
print(f"{units} x {price:.2f} = {units * price:>8.2f}")Poetic Bytes teaches Python for free 6 words POETIC BYTES TEACHES PYTHON FOR FREE poetic-bytes-teaches-python-for-free True False Poetic Bytes teaches Python for everyone 12 x 2.50 = 30.00
Line by line
- 1A string with extra spaces at both ends.
- 3-4
strip()removes the spaces andsplit()breaks the text into a list of words. - 5-8Print the clean text, the word count, an upper-case copy and a lower-case slug joined with hyphens.
- 9-10
startswithandendswithreturn True or False. - 12-13An f-string with
:.2ffor two decimals and:>8.2fto right-align in a width of eight.
Lists and comprehensions
A list holds an ordered collection that you can change. You will add to it, slice it, sort it and loop over it constantly. A list comprehension builds a new list from an old one in a single readable line, and it can include a condition to filter as it goes.
Sorting deserves a note: sorted() returns a new list while .sort() changes the list in place. The key argument lets you sort by any rule, such as length or the second item of a pair.
Practise by changing the filter or the sort key. More on collections is in the lists lesson and the comprehensions lesson.
Comprehensions look dense at first, so read them aloud: take n for each n in numbers, if n is even. The sentence and the code have the same shape. When a comprehension becomes hard to read, a normal loop is a perfectly good choice, because clarity matters more than being short.
numbers = [7, 3, 12, 5, 18, 2, 9] evens = [n for n in numbers if n % 2 == 0] squares = [n * n for n in numbers] print(evens) print(squares[:3]) print(sorted(numbers)) print(sorted(numbers, reverse=True)[:3]) names = ["maria", "Al", "Jonathan", "li"] print(sorted(names, key=len)) print(sorted(names, key=str.lower)) print(sum(numbers), max(numbers), min(numbers))
[12, 18, 2] [49, 9, 144] [2, 3, 5, 7, 9, 12, 18] [18, 12, 9] ['Al', 'li', 'maria', 'Jonathan'] ['Al', 'Jonathan', 'li', 'maria'] 56 18 2
Line by line
- 3-4Two comprehensions: even numbers only, and every number squared.
- 5-6Print the evens and the first three squares using a slice
[:3]. - 7-8
sortedreturns a new ordered list;reverse=Truegives the three largest. - 10-12Sort names by length and then alphabetically ignoring case with
key. - 13
sum,maxandminsummarise a list.
Dictionaries and counting
A dictionary maps keys to values, which makes it the right tool for lookups, counts and grouping. The get method reads a key with a default instead of raising an error, and collections.Counter counts items for you in one line.
Loop over items() to get keys and values together. Dictionaries remember insertion order, so output is predictable. Merging two dictionaries is as short as using the | operator.
Use these patterns for word counts, inventories and settings. The full story is in the dictionaries lesson.
Counting and grouping are two of the most common jobs in everyday programs, from word frequencies to sales by region. Once you recognise the pattern of a dictionary that maps something to a number or a list, you will see where to use it everywhere.
from collections import Counter
stock = {"apple": 4, "pear": 0, "plum": 9}
print(stock["apple"], stock.get("kiwi", "none"))
stock["kiwi"] = 6
for fruit, count in stock.items():
print(f"{fruit:6} {count}")
text = "the cat and the hat and the bat"
counts = Counter(text.split())
print(counts.most_common(2))
defaults = {"theme": "dark", "size": 12}
custom = {"size": 16}
print(defaults | custom)4 none
apple 4
pear 0
plum 9
kiwi 6
[('the', 3), ('and', 2)]
{'theme': 'dark', 'size': 16}Line by line
- 3-4A dictionary of stock levels.
getreturns a fallback when the key is missing. - 5-7Add a key and loop through keys and values with
items(). - 9-11
Countercounts words;most_common(2)returns the two most frequent. - 13-15Merge two dictionaries with
|; the right-hand values win.
Functions and testing them
A function packages a piece of logic under a name. Give it clear parameters, return a value instead of printing inside it, and it becomes easy to reuse and easy to test. Default parameter values keep calls short.
Testing can begin with plain assert statements. An assert says: this must be true, otherwise stop. A handful of asserts under a function is a perfectly good first test suite, and it catches mistakes the moment you change something.
Try adding a test for a case you worry about, such as an empty string. The functions lesson goes further into arguments and scope.
Small functions with one clear purpose are easier to name, test and reuse. If you cannot describe what a function does in one sentence, it probably does two things and can be split. Splitting early costs little and pays back every time you change the code.
def average(values, digits=2):
if not values:
return 0.0
return round(sum(values) / len(values), digits)
def is_palindrome(text):
cleaned = [c.lower() for c in text if c.isalnum()]
return cleaned == cleaned[::-1]
assert average([2, 4, 6]) == 4
assert average([]) == 0.0
assert average([1, 2], digits=1) == 1.5
assert is_palindrome("A man, a plan, a canal: Panama")
assert not is_palindrome("Poetic Bytes")
print("all tests passed")
print(average([3, 4, 8]), is_palindrome("Level"))all tests passed 5.0 True
Line by line
- 1-4
averagehandles an empty list first, then rounds the mean to a chosen number of digits. - 7-9
is_palindromekeeps only letters and digits in lower case, then compares the list with its reverse. - 12-16Five asserts act as tests. If any fails, Python stops with an
AssertionError. - 17Print results from the same functions to see them in action.
Write the test for a bug before you fix it. The test proves the fix works and stops the bug coming back.
Files and paths
Reading and writing files is how programs remember anything. The safe pattern is the with statement, which closes the file for you even if an error happens. pathlib makes paths readable and works on every operating system.
In the browser examples I use a temporary folder that disappears afterwards, so nothing is left behind. On your own computer, the same code works on real folders by changing the path.
For more, read the files lesson and the automation lesson where files are organised in bulk.
Notice that every file example writes to a temporary place. When you move to real files, work on a copy first and check the result before pointing a script at anything important. Careful habits matter more with files than almost anywhere else, because mistakes are permanent.
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
notes = Path(tmp) / "notes.txt"
notes.write_text("first line\nsecond line\n")
with notes.open("a") as handle:
handle.write("third line\n")
lines = notes.read_text().splitlines()
print(len(lines), "lines")
for number, line in enumerate(lines, start=1):
print(number, line.upper())
print(notes.exists(), notes.suffix, notes.stat().st_size, "bytes")3 lines 1 FIRST LINE 2 SECOND LINE 3 THIRD LINE True .txt 34 bytes
Line by line
- 4-6Create a temporary folder, build a path with
/and write two lines. - 8-9Open the same file in append mode and add a third line.
- 11-14Read the whole text, split it into lines and print each with a number.
- 15Check that the file exists and print its extension and size.
Classes and dataclasses
A class bundles data with the actions that belong to it. Write one when you have several things that should travel together, such as a name, a balance and the rules for changing it. Methods receive the object as self and can protect its data.
A dataclass is the short form for mostly-data classes. You list the fields and Python writes the constructor and the readable representation for you.
Compare the two below. You can see classes used in full projects: the office system, the library system and the polymorphism examples.
Classes are best learned by modelling something you know. A bank account, a library book or a game character each makes the idea of data plus behaviour feel natural. If a class has only fields and no methods, a dataclass or even a dictionary may be enough.
from dataclasses import dataclass
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be positive")
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("not enough money")
self.balance -= amount
@dataclass
class Point:
x: float
y: float
acct = Account("Ana", 100)
acct.deposit(50)
acct.withdraw(30)
print(acct.owner, acct.balance)
try:
acct.withdraw(500)
except ValueError as error:
print("refused:", error)
p = Point(3, 4)
print(p, (p.x ** 2 + p.y ** 2) ** 0.5)Ana 120 refused: not enough money Point(x=3, y=4) 5.0
Line by line
- 4-17
Accountstores an owner and a balance and protects them with rules indepositandwithdraw. - 20-23
Pointis a dataclass: just the fields, with the constructor generated. - 26-32Use the account, then show that an invalid withdrawal is refused with an error.
- 34-35Create a point and compute its distance from the origin.
Errors and clean exits
Errors are normal. A good program expects the ones that can reasonably happen and handles them. Put the risky line in try, catch the specific error in except, and use else and finally for code that depends on success or must always run.
Catch specific exceptions such as ValueError, not a bare except, which would also hide your own typing mistakes. Raise your own errors with a clear message when your function receives something it cannot accept.
The helper below turns messy user input into a number or a friendly message. Keep this pattern handy; it appears in nearly every program that reads input.
Good error handling is mostly about deciding who is responsible. If the user can fix the problem, show a friendly message. If the programmer made a mistake, let it fail loudly so the bug gets found. Mixing the two up leads to programs that either crash on harmless input or silently hide real faults.
def parse_age(text):
try:
age = int(text)
except ValueError:
return f"{text!r} is not a number"
else:
if not 0 <= age <= 120:
return f"{age} is not a realistic age"
return f"age {age} accepted"
finally:
print("checked", repr(text))
for entry in ["42", "forty", "-5", "200"]:
print(parse_age(entry))checked '42' age 42 accepted checked 'forty' 'forty' is not a number checked '-5' -5 is not a realistic age checked '200' 200 is not a realistic age
Line by line
- 2-5Try converting text to an integer; if that fails, return a friendly message.
- 6-9
elseruns only when no error happened, and validates the range. - 10-11
finallyalways runs, so the check is logged for every input. - 14-15Loop over four inputs: valid, not a number, too small and too large.
Handy standard library tools
Python ships with a large standard library, and knowing a few corners of it saves hours. datetime handles dates, random with a seed gives repeatable pseudo-random values, json converts data to text and back, and itertools builds iterators for pairs, groups and combinations.
Seeding the random generator is a useful trick for examples and tests. The same seed always gives the same numbers, so results are predictable while still behaving like random data.
Browse the lessons on modules and JSON once you have tried these.
The standard library is the most underused resource in Python. Before installing a package for a small job, check whether a module in the standard library already does it. Fewer dependencies mean fewer things that can break, and code that runs anywhere.
import json
import random
from datetime import date, timedelta
from itertools import combinations
random.seed(7)
print([random.randint(1, 6) for _ in range(5)])
start = date(2026, 1, 30)
print(start + timedelta(days=3), (date(2026, 12, 25) - start).days, "days to go")
data = {"name": "Ana", "scores": [90, 85]}
text = json.dumps(data)
print(text)
print(json.loads(text)["scores"][0])
print(list(combinations(["a", "b", "c"], 2)))[3, 2, 4, 6, 1]
2026-02-02 329 days to go
{"name": "Ana", "scores": [90, 85]}
90
[('a', 'b'), ('a', 'c'), ('b', 'c')]Line by line
- 6-7With a fixed seed, five dice rolls come out the same every run.
- 9-10Add three days to a date and count days until Christmas.
- 12-15Convert a dictionary to JSON text and back.
- 17
combinationslists every pair from three letters.
These examples use only the standard library, so they run anywhere Python is installed with no extra packages.
Where to go next
Once the examples feel comfortable, move from snippets to projects, because projects force you to combine ideas. Good next steps on Poetic Bytes are the office system, the library system, the log router and the automation lesson. Smaller walk-throughs include chess pieces, the garage, robots, the media player, the recipe formatter, the protocol checker, the image filter plugin and the lessons on inheritance and polymorphism.
A simple practice routine works well: choose one example a day, predict the output before running it, run it, and then change one thing. Keep a notes file of surprises, because surprises mark the exact places where your mental model needs to improve.
The program below prints a four week practice plan. It is only a few lines, but it shows how plain Python can help you organise your own learning.
Keep a small file of your own favourite snippets. Every time you solve a problem in a way you like, paste it there with a one line note. After a few months you will have a personal reference that fits the way you think, which is more useful than any generic cheat sheet.
plan = {
"Week 1": ["strings", "lists", "dictionaries"],
"Week 2": ["functions", "errors", "files"],
"Week 3": ["classes", "dataclasses", "modules"],
"Week 4": ["office system", "library system", "log router"],
}
for week, topics in plan.items():
print(f"{week}: " + ", ".join(topics))
total = sum(len(topics) for topics in plan.values())
print(f"{total} topics, about {total * 2} hours at two hours each")Week 1: strings, lists, dictionaries Week 2: functions, errors, files Week 3: classes, dataclasses, modules Week 4: office system, library system, log router 12 topics, about 24 hours at two hours each
Line by line
- 1-6A dictionary mapping each week to a list of topics.
- 8-9Loop through the plan and print each week on one line with
join. - 11-12Count the topics and estimate the total study time.
Common mistakes
β Reading without running
Code that you only read feels clear and teaches little. Run each example and change one thing.
β Copying without predicting
Before pressing Run, write down what you expect to see. The gap between prediction and result is where you learn.
β Catching every error with a bare except
A bare except hides real bugs. Catch the specific errors you expect.
β Printing inside functions instead of returning
Returned values can be tested and reused. Printing is for the edges of the program.
β Skipping the tests
Even three assert lines under a function catch mistakes early and give you the confidence to change code.
Quick quiz
Tap an answer. I explain every one, right or wrong.
Q1. What does sorted(items) do?
sorted returns a new list and leaves the original unchanged.Q2. Which gives a default when a dictionary key is missing?
get returns the default instead of raising KeyError.Q3. What is the safest way to open a file?
with closes the file automatically even when an error occurs.Q4. What does assert do when its condition is false?
AssertionError, which is how simple tests report failure.Q5. Why seed the random generator in examples?
Q6. Which is a good habit when practising?
Frequently asked questions
Do I need to install anything to run these?
+No. Each example runs in your browser using Pyodide, and uses only the standard library.
Can I change the code?
+Yes, the code boxes are for experimenting. Edit, press Run and read the output or the error.
Where are the full lessons?
+Each section links to the lesson for its topic. The home page lists every lesson and project.
How do I run these on my own computer?
+Save a block as a .py file and run python3 file.py. The code is ordinary Python.
What should I build after these?
+Pick a project such as the library system or the office system. Projects make you combine several ideas at once.
Key takeaways
- βShort examples are the fastest route to understanding a feature.
- βPredict the output, run the code, then change one thing.
- βReturn values from functions and test them with
assert. - βUse
withfor files and specificexceptclauses for errors. - βDataclasses shorten classes that are mostly data.
- βMove from snippets to small projects as soon as the basics feel familiar.