This page is a library of short Python examples, each solving one everyday task with the output shown and the important lines explained. They use only the standard library, so you can paste any of them into a .py file and run it.
def equipment_report(requests):
totals = {}
for item, quantity in requests:
totals[item] = totals.get(item, 0) + quantity
return totals
print(equipment_report([("cones", 3), ("lamps", 2), ("cones", 4)]))
# {'cones': 7, 'lamps': 2}The examples cover counting, filtering, cleaning text, parsing files, summarising with dictionaries and modelling with a class, using a youth sports club's equipment store. Just as important as the code is how to learn from an example: choosing one that matches your question, tracing it by hand, changing one thing at a time, and combining small examples into a program. Each topic links to its full lesson.
Example selection
A useful example answers one concrete question with clear inputs and outputs. Before copying one, identify:
- Input: what data does it expect, in what shape? A list of
(item, quantity)tuples is different from a dictionary. - Output: does it return a value, print, or change something in place?
- Assumptions: does it assume no negative quantities, unique names, sorted data, a file that exists?
| Task | Pattern | Lesson |
|---|---|---|
| count occurrences | dictionary with get(key, 0) + 1, or Counter | dictionaries |
| keep matching items | list comprehension with if | comprehensions |
| tidy text | strip(), lower(), split() | strings |
| read rows from a file | csv.DictReader | CSV handling |
| group related data and behaviour | a class or dataclass | classes |
Copying a program without its assumptions is a common source of bugs: an example that assumes quantities are integers will silently misbehave when your data contains "3" as text.
Tracing
Trace an example by hand before running it: write down each variable's value after each line. For equipment_report above:
item quantity totals
cones 3 {'cones': 3}
lamps 2 {'cones': 3, 'lamps': 2}
cones 4 {'cones': 7, 'lamps': 2}Then run the code and compare. If your prediction was wrong, you've found exactly the part you didn't understand, which is far more useful than reading a correct output.
Output alone can hide behaviour. A function might print the right total but also change the list it was given, or keep state between calls. Add print() calls or use the = specifier, print(f"{totals=}"), at key points, or step through with the debugger, to see what happens inside, not just what comes out.
Variation
Once an example works, change one meaningful assumption and predict the result before running it:
- Add an item that appears once: does it show up correctly?
- Pass an empty list: does it return
{}or crash? - Add a negative quantity, representing a returned item: is that allowed or should it raise an error?
- Use mixed capitalisation,
"Cones"and"cones": should they be counted together?
print(equipment_report([])) # {}
print(equipment_report([("Cones", 1), ("cones", 2)])) # counted separatelyEach variation tests one idea. Changing several details at once makes it impossible to tell which change caused a difference. If a variation reveals behaviour you don't want, such as separate counts for "Cones" and "cones", fix it explicitly and add the case to your tests.
Combining examples
Real programs are built by joining small, well-defined functions. Each function should take its inputs as parameters and return its result, rather than reading or changing global variables, so pieces can be combined and tested independently:
def parse_requests(lines):
for line in lines:
item, qty = line.split(",")
yield item.strip().lower(), int(qty)
def format_report(totals):
return "\n".join(f"{item:<8}{qty:>3}" for item, qty in sorted(totals.items()))
lines = ["Cones, 3", "lamps,2", "cones, 4"]
print(format_report(equipment_report(parse_requests(lines))))parse_requests cleans the text, equipment_report counts, and format_report presents. Each can be tested on its own, and replacing one, such as reading from a CSV file instead of a list, doesn't affect the others. A function that depends on an unexplained global variable can't be reused this way, because it only works in the program it was written in.
Independent practice and a worked check
Task: build an original mini library of counting, filtering, formatting, file parsing and class-based examples with one documented assumption each. Start from this template:
"""Equipment examples. Each function states one assumption."""
def count_items(names):
"""Assumes names are already lower-case."""
counts = {}
for name in names:
counts[name] = counts.get(name, 0) + 1
return counts
def available(stock, minimum):
"""Assumes quantities are integers."""
return sorted(item for item, qty in stock.items() if qty >= minimum)
def label(item, qty):
"""Assumes qty is non-negative."""
return f"{item.title():<10}{qty:>4}"
print(count_items(["cones", "bibs", "cones"])) # {'cones': 2, 'bibs': 1}
print(available({"cones": 20, "nets": 1}, 5)) # ['cones']
print(label("cones", 20)) # Cones 20Add a CSV-parsing function and a class of your own, each with its assumption, then write one variation test per function. For the worked check, before adapting an example you should identify its inputs, outputs and assumptions.
Reference and next practice
The official Python tutorial contains many runnable examples. Continue with coding challenges and practice problems, and try the Python exercises and Python quiz.
Python Examples Library Summary
- Example selection: Choose an example that answers one concrete question with explicit inputs and outputs.
- Tracing: Trace values through each statement before running the program.
- Variation: Changing one meaningful assumption tests whether the underlying idea is understood.
- Combining examples: Join small functions through clear input and return contracts.
Python Examples Library Examples
Each example shows the code, the output it produces and what each part does.
Python Examples Library in a small program
def equipment_report(requests):
totals = {}
for item, quantity in requests:
totals[item] = totals.get(item, 0) + quantity
return totals
print(equipment_report([("cones", 3), ("lamps", 2), ("cones", 4)])){'cones': 7, 'lamps': 2}Line-by-line explanation
- Line 2An empty dictionary will hold one total per item.
- Lines 3 to 4Each request adds its quantity to the item's running total;
get(item, 0)supplies 0 the first time. - Line 7Cones appear twice, so their quantities are added: 3 + 4.
Filter and sort with a comprehension
kit = [("bibs", 12, "good"), ("balls", 3, "worn"), ("cones", 20, "good"), ("nets", 1, "torn")]
needs_replacing = [name for name, qty, condition in kit if condition != "good"]
low_stock = sorted((qty, name) for name, qty, _ in kit if qty < 5)
print("Replace:", needs_replacing)
print("Low stock:", low_stock)Replace: ['balls', 'nets']
Low stock: [(1, 'nets'), (3, 'balls')]Line-by-line explanation
- Line 3The
iffilters rows; only items not in good condition are kept. - Line 4Building
(qty, name)tuples makessorted()order by quantity first.
Clean and count words in text
from collections import Counter
feedback = "Great coaching! great kit, but the kit room is CLOSED too often."
words = [w.strip(".,!").lower() for w in feedback.split()]
counts = Counter(words)
print(counts.most_common(2))
print(len(words), "words,", len(counts), "distinct")[('great', 2), ('kit', 2)]
12 words, 10 distinctLine-by-line explanation
- Line 4
split()handles the double space;strip(".,!")removes punctuation from each word's ends. - Line 5
Countercounts every word in one call.
Parse CSV text and total by category
import csv, io
data = io.StringIO("item,team,qty\ncones,under-10s,6\nballs,under-12s,4\ncones,under-12s,5\n")
by_team = {}
for row in csv.DictReader(data):
by_team[row["team"]] = by_team.get(row["team"], 0) + int(row["qty"])
for team, qty in sorted(by_team.items()):
print(f"{team}: {qty}")under-10s: 6
under-12s: 9Line-by-line explanation
- Line 3
StringIOstands in for a file, so the example runs without creating one. - Line 6CSV values are text, so
int()converts each quantity before adding.
A small class with validation
class Store:
def __init__(self):
self.stock = {}
def add(self, item, qty):
if qty <= 0:
raise ValueError("quantity must be positive")
self.stock[item] = self.stock.get(item, 0) + qty
def lend(self, item, qty):
if self.stock.get(item, 0) < qty:
raise ValueError(f"only {self.stock.get(item, 0)} {item} available")
self.stock[item] -= qty
store = Store()
store.add("balls", 6)
store.lend("balls", 4)
print(store.stock)
try:
store.lend("balls", 5)
except ValueError as error:
print("Refused:", error){'balls': 2}
Refused: only 2 balls availableLine-by-line explanation
- Lines 5 to 8Validation lives inside the method, so every caller gets the same rule.
- Lines 10 to 13Lending more than is available raises a clear error instead of producing negative stock.
Common Python Examples Library Mistakes
Copying an example without its assumptions
rows = [("cones", "3"), ("cones", "4")] # quantities read as text
print(equipment_report(rows)) # TypeError: 0 + "3"rows = [("cones", "3"), ("cones", "4")]
print(equipment_report((item, int(qty)) for item, qty in rows))The example assumed integer quantities; convert data to match an example's assumptions before using it.
A reusable function that depends on a global
stock = {"balls": 6}
def lend(item, qty):
stock[item] -= qty # only works with this one global dictionarydef lend(stock, item, qty):
stock[item] -= qty
return stockPython Examples Library in Real Projects
Learning from examples effectively
Experienced developers read and adapt examples all the time: documentation snippets, Stack Overflow answers, open-source code. What separates effective use from copy-paste is the habit shown here: identify inputs, outputs and assumptions, trace before running, vary one thing, and wrap the result in a small function with tests.
Building your own library of solved examples is also a good revision tool. Keep each one in a file with a comment stating the question it answers and one assumption it makes, and you'll have a personal reference that grows with the course.
Python Examples Library FAQ
Where can I find Python examples for beginners?
This page and the examples in every lesson of this course run with the standard library and show their output. The official Python tutorial and the documentation for each module also include examples. Start with short programs that solve one task, and run each one yourself.
How should I practise with Python examples?
Predict the output before running, trace variable values by hand, then change one thing at a time, such as an empty input or an unusual value, and predict again. Finally, rewrite the example from memory as a function with a test.
Is it okay to copy Python code examples?
Copying to learn is fine, but understand every line and its assumptions first. For code you publish or ship, check the licence of the source and test the code with your own data, including edge cases.
What are good first Python programs to write?
A tip calculator, a word counter, a number-guessing game, a to-do list saved to a file and a simple grade report. Each uses variables, conditions, loops, functions and collections, and can be extended step by step.
How do I run a Python example from this page?
Save the code in a file such as example.py, open a terminal in that folder and run python example.py (or python3 on macOS and Linux). The Python introduction explains installation and running files.
Python Examples Library Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
What should you identify before adapting an example?
Which review concern is valid for Python examples library?
Python Examples Library Quiz
2 questions to check what you learned.
What should you identify before adapting an example?
- Only its line count
- Its inputs, outputs and assumptions
- Python ignores the distinction
Which statement correctly describes variation?
- Changing one meaningful assumption tests whether the underlying idea is understood.
- Only the example output matters, not the rule
- Every operation has the same behavior