Values, Control Flow, Functions and Classes
Read and write everyday Python: values and names, branches and loops, functions with clear signatures, and classes, including a subclass of a library base class.
Contentsand lesson path
On this page
- Why it matters
- Values, types and names
- Branches and loops
- Functions: inputs, outputs and defaults
- Classes: data with behaviour
- Subclassing a library base class
- Check your understanding
- Apply it
- Review prompt
Lessons of Python Foundations
- Values, Control Flow, Functions and Classes Concept · 25 min
- Choosing Lists, Dicts, Sets, Tuples and Dataclasses Worked example · 20 min
- Exceptions and Defensive Input Handling Worked example · 15 min
- Modules, Packages and Virtual Environments Lab · 25 min
- Type Hints and Tests with pytest Lab · 25 min
- Check: Read, Fix and Test a Script Knowledge check · 6 questions
What you will learn
- Write functions that use core data structures (lists, dicts, sets, tuples) and handle errors with exceptions.
01. Why it matters
Most AI-engineering code is not model maths. It is glue: read a file of support tickets, clean the text, estimate token counts, call a model and shape the result. That glue is plain Python, and when it breaks it usually breaks at a basic level: a list changed through a second name, a branch that matches more than you meant, a function that quietly returns None, or a subclass that never set up its parent.
This lesson covers values and names, control flow, functions and classes, using Python 3.12 or later. Type each snippet into a Python prompt (run python3 in a terminal) and compare the output with the comments.
02. Values, types and names
Every value in Python is an object with a type: 42 is an int, 3.5 a float, "refund" a str and True a bool. None is the single value of its own type and stands for nothing here. A variable is a name bound to an object, not a box holding a copy. Assignment never copies anything; it makes one more name refer to the same object.
That matters because some types are mutable: lists, dicts, sets and most objects you define can change in place. Others are immutable: numbers, strings, tuples and None never change, so any operation that seems to modify them produces a new object. Change a mutable object through one name and every other name bound to it sees the change.
tokens = ["refund", "late", "refund"]
alias = tokens # a second name for the same list
alias.append("urgent")
print(tokens) # ['refund', 'late', 'refund', 'urgent']
count = 3
total = count
total += 1 # ints are immutable: total now names a new object
print(count, total) # 3 4Two more rules prevent confusion. / on two integers always produces a float (7 / 2 is 3.5), while // rounds down (7 // 2 is 3) and % gives the remainder. And every value has a truth value: zero, empty strings, empty containers and None count as false, so if tickets: reads as if there are any tickets. Use == to compare values, and keep is for if result is None:.
03. Branches and loops
if, elif and else choose one branch. Python tests the conditions from the top and runs the first block whose condition is true, then skips the rest. Indentation, four spaces by convention, marks where each block starts and ends; there are no braces. The function below routes a support ticket by its subject line.
def triage(subject: str) -> str:
text = subject.lower()
if "outage" in text or "down" in text:
return "urgent"
elif "refund" in text:
return "billing"
else:
return "general"
subjects = ["Site down since 9am", "Refund for order 1182", "How do I export data?"]
for number, subject in enumerate(subjects, start=1):
print(number, triage(subject))1 urgent
2 billing
3 generalA for loop walks over any iterable: a list, a string, the lines of a file or the keys of a dict. Use enumerate() when you also need a position and range(n) for the numbers 0 to n - 1. A while loop repeats while its condition holds, which suits work with an unknown number of steps, such as polling until a batch job finishes.
break leaves a loop early and continue jumps to the next item. The function below packs retrieved chunks into a prompt, in order, until the next one would overflow the token budget.
def fit_to_budget(chunk_tokens: list[int], budget: int) -> int:
"""Return how many chunks fit, in order, inside the token budget."""
used = 0
taken = 0
for tokens in chunk_tokens:
if used + tokens > budget:
break
used += tokens
taken += 1
return taken
print(fit_to_budget([120, 300, 250, 90], budget=600)) # 2The third chunk would bring the total to 670, so the loop stops after two. The fourth chunk would have fitted on its own, but break ends the loop for good; to skip chunks that do not fit and keep trying the rest, you would use continue. Either can be right, so choose deliberately and say which in the docstring.
04. Functions: inputs, outputs and defaults
A function puts one step of your program behind a name, so you can test it and reuse it. Its signature is its contract: the parameters it takes, their types (written as hints, which a later lesson in this skill checks with a tool) and what it returns. A few rules are worth learning early:
- Parameters can have default values, and callers can pass arguments by keyword, which makes a call explain itself:
estimate_tokens(text, chars_per_token=3.0). - A function without a
returnstatement returnsNone. A caller that stores or prints the result getsNone, not an error, so the mistake shows up somewhere else later. - To hand back several values, return a tuple and unpack it at the call site:
first, last = shortest_and_longest(words). - Default values are evaluated once, when the
defstatement runs, and then shared by every call. Never use a mutable default such as[]or{}; default toNoneand create the object inside the function. - Functions are values too. You can pass one as an argument, as with
key=lenbelow, which tellsmin()andmax()what to compare.
def estimate_tokens(text: str, chars_per_token: float = 4.0) -> int:
"""Rough estimate: English text averages about four characters per token."""
return max(1, round(len(text) / chars_per_token))
def shortest_and_longest(words: list[str]) -> tuple[str, str]:
return min(words, key=len), max(words, key=len)
print(estimate_tokens("Where is my refund?")) # 5
print(estimate_tokens("Where is my refund?", chars_per_token=3.0)) # 6
first, last = shortest_and_longest(["model", "a", "tokeniser"])
print(first, last) # a tokeniserFour characters per token is only a rule of thumb; real counts depend on the model's tokeniser. Because the assumption lives in one named function, you can replace it in one place later. That is the practical case for small functions.
05. Classes: data with behaviour
A class bundles data with the operations that keep that data consistent. Calling the class creates an instance, and Python then runs the special method __init__ to give the new instance its starting attributes. Every method receives the instance as its first parameter, called self by convention; that is how a method reads and updates the attributes of the particular instance it was called on.
class TokenBudget:
"""Track tokens spent against a fixed limit."""
def __init__(self, limit: int) -> None:
self.limit = limit
self.used = 0
def spend(self, tokens: int) -> bool:
"""Record the spend and return True, or return False if it would overrun."""
if self.used + tokens > self.limit:
return False
self.used += tokens
return True
def remaining(self) -> int:
return self.limit - self.used
budget = TokenBudget(limit=1000)
print(budget.spend(400), budget.spend(700), budget.remaining()) # True False 600Each instance keeps its own attributes, so two budgets never interfere. The class earns its place because spend() enforces a rule: no caller that uses it can push used past limit. When a value is just a bundle of fields with no rule to protect, the next lesson shows how dataclasses write __init__ and a readable printout for you.
06. Subclassing a library base class
Libraries often give you a base class and ask you to fill in a few methods; the base class runs the process and calls your methods at the right moments. You will meet this in web frameworks, logging handlers and deep-learning libraries, where every model is a subclass of a base module class.
One rule catches people out. Once your subclass defines its own __init__, Python no longer runs the parent's __init__ for you. Call it yourself with super().__init__(...), normally first, so the parent can create the state its methods rely on. The standard library's HTMLParser shows this safely: it reads HTML and calls your handle_data() method for each run of text, which is handy for turning help-centre pages into plain text.
from html.parser import HTMLParser
class TextExtractor(HTMLParser):
"""Collect the visible text of an HTML page, such as a help-centre article."""
def __init__(self) -> None:
super().__init__() # let HTMLParser set up its own state first
self.chunks: list[str] = []
def handle_data(self, data: str) -> None:
# HTMLParser calls this method for every run of text between tags.
if data.strip():
self.chunks.append(data.strip())
parser = TextExtractor()
parser.feed("<h1>Refunds</h1><p>Refunds take <b>5 days</b>.</p>")
print(parser.chunks)['Refunds', 'Refunds take', '5 days', '.']Delete the super().__init__() line and nothing complains at first: the class is accepted and creating an instance works. The failure arrives when you call feed(). It stops with an AttributeError such as 'TextExtractor' object has no attribute 'rawdata' (the internal name differs between Python versions), because the parent never created its parsing state. An AttributeError naming an attribute you never wrote is the usual sign of a missing super().__init__().
07. Check your understanding
a = ["x"]
b = a
b = b + ["y"]
print(a)08. Apply it
Start the skill's practice project: a command-line tool that counts word frequencies in a text file. In a new folder, create wordfreq.py and write:
- A function
count_words(text: str) -> dict[str, int]that lower-cases the text, splits it withstr.split()and counts each word with aforloop and anifthat checks whether the word is already a key. - A function
most_common(counts: dict[str, int]) -> strthat returns the word with the highest count, and returns an empty string whencountsis empty. - A few
print()calls at the bottom that run both functions on a sample sentence, and once on an empty string.
Keep the file. The next lessons replace the counting loop with better data structures, then add error handling, packaging and tests. Stretch: extend TextExtractor so it ignores the text inside script and style elements. HTMLParser also calls handle_starttag() and handle_endtag(), which you can override to track where you are.
09. Review prompt
Without scrolling back, answer these in your own words, then check them against the lesson:
- Why does appending to a list through one name change what another name sees, while
total += 1on an integer does not? - When would you pick
whileoverfor, andcontinueoverbreak? - What does a function return if it has no
returnstatement, and why can that hide a bug? - What is
self, and what runs when you callTokenBudget(limit=1000)? - A subclass of a library class fails with an
AttributeErrorabout an attribute you never wrote. What do you check first?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.