Python Data Automation · Chapter 1 of 10

Python Basics and Control Flow

Use variables, expressions, conditionals, and loops to control program behavior with clear branch logic.

Why this chapter matters

Control flow is the foundation of every script because it decides which operations run, when they run, and how many times.

What you will learn

  • Write and evaluate simple Python expressions with correct types.
  • Use if, elif, and else blocks to encode decision rules.
  • Choose for and while loops based on the shape of the task.

Understand the core ideas

Control flow is how a Python script turns a business rule into concrete behavior. A variable holds state, an expression computes a value, and a conditional decides what path to run next. When these pieces are clear, you can inspect a script and predict exactly what it will do for each record. That predictability matters in automation, where one hidden branch can misclassify thousands of rows. A good practice is to name intermediate values, keep conditions readable, and make each branch mutually exclusive so one record cannot match two outcomes.

Loops apply those decisions repeatedly. A for loop is best when you already have a collection such as a list of orders, while a while loop is best when work continues until a condition changes. In both cases, write guards that prevent infinite loops and unexpected state drift. Error handling is also part of control flow, not a separate concern. If converting text amounts to numbers can fail, use try and except around the conversion and route bad rows to an exception list instead of crashing the full run. This keeps pipeline behavior explicit and auditable.

Key terms

branch
A decision path selected by if, elif, or else based on a boolean condition.
iteration
One pass through a loop body while processing items or state.
predicate
A true or false expression used to decide whether logic should run.
exception path
A controlled fallback route for inputs that fail validation or parsing.

Classify order statuses with safe amount parsing

You receive rows with order_id, amount_text, and shipped_flag. The goal is one final status per row: shipped, pending, or exception. Amounts arrive as strings and some values are invalid, so parsing must be guarded.

  1. Create an empty list called results and iterate through each row with a for loop so every record is processed exactly once.
  2. Inside the loop, parse amount_text with float in a try block. If parsing fails, append status exception with a reason like invalid_amount and continue to the next row.
  3. If parsing succeeds, evaluate shipped_flag first. If true, assign shipped. If false and amount is greater than zero, assign pending. Otherwise assign exception for non_positive_amount.
  4. Append a normalized output record with order_id, parsed amount when available, and the selected status. Keep the branch order stable so classification is deterministic.
Result: The script produces one status per input row, invalid amounts are captured without stopping the run, and branch logic is easy to review during debugging. This pattern scales cleanly to larger datasets because success and failure paths are both explicit.

A common misconception

Claim: If logic works for a few rows, it is safe to run at scale without extra guards.

Correction: Small samples often miss malformed data. Add explicit branch ordering, parse guards, and exception capture so the script remains correct when real input variability appears.

Lessons in this chapter

  1. Values, variables, and expressionsCreate variables and predict expression results.
  2. Conditionals with if and elifBuild decision trees that are complete and non-overlapping.
  3. Looping with for and whileIterate through collections and state-driven conditions.
  4. Guide: basics and control flowApply fundamentals to classify and validate records. Read the full guide →

Study task

Write a script that loops through order records and assigns each order one status: shipped, pending, or exception.

Chapter checkpoint

When should you choose a for loop instead of a while loop?

Use a for loop when iterating over a known collection or range. Use a while loop when repetition depends on a changing condition.

Learn this with an AI teacher that starts from what you already know.

Tell LearnLive your goal and starting point, and it adapts the explanations, examples, and practice as you go.

Teach me this