Control flow and comprehensions
Control flow and comprehensions
Python's control flow has no surprises in its keywords. if, elif, else, for, while, break, and continue do what they do everywhere. What is different is what they operate on. A for loop iterates over any iterable rather than counting an index, an if tests truthiness rather than a strict boolean, and since Python 3.10 there is a match statement that takes apart nested data by shape. Get comfortable with those three and the language stops fighting you.
Comprehensions are the other half of this lesson. Most loops in a backend exist to build one collection from another: the open tickets from all tickets, a dict of tickets by id, the set of tags in use. Python has a dedicated syntax for exactly that, and idiomatic code uses it wherever the loop body is a single expression.
Continue reading
Pro unlocks every video lesson, the full notes and runnable code across the Python with AI course, from the language itself to agents, MCP, Langfuse and deployment.