Python control flow is the set of rules that decides which code runs and how many times it runs. Use if and elif for decisions, for loops for known collections, and while loops only when a stop condition is explicit and tested.
- Write clear conditions first, then write the branch code under each condition.
- Prefer for loops when iterating over rows, files, or lists.
- Keep loop bodies short and log key values when debugging behavior.
Use conditionals to encode business rules
A script is easier to trust when each branch maps to a plain-language rule. For example, classify an order as pending if paid is false, shipped if tracking is present, and exception if required fields are missing.
Python uses indentation to define blocks, so alignment is part of the syntax. Consistent indentation prevents accidental branch nesting and makes reviews faster.
Choose loop shape based on data shape
Use for item in items when processing a known sequence. Use enumerate when index context helps with logging or row-level validation messages. Use while only when the next step depends on state that changes each cycle.
- Break long loops into helper functions for readability.
- Guard loops with input checks to avoid runtime failures on empty data.
- Add explicit stop conditions before writing while loops.
Classify order records from a list
A list of dictionaries contains order_id, paid, and tracking_code for a daily operations check.
- Create a for loop that iterates through each order record.
- Use if and elif to label each record as shipped, pending, or exception.
- Append the label to a results list and print counts by label at the end.
Common mistakes
- Mixing tabs and spaces, which can raise indentation errors.
- Using while loops for tasks that should be simple for loops.
- Writing overlapping conditions where multiple branches could apply.
- Changing source records in place before validation is complete.
Try one
When processing a list of orders once, which loop is usually the best default choice?
A for loop, because the collection length is known and each item should be handled once.
Sources
- Python documentationOfficial reference for Python syntax, standard library modules, and tutorials.