Sign in to save

Bookmark this page so you can find it later.

Sign in to save

Bookmark this page so you can find it later.

Control flow is how a program decides what to do next instead of simply running every line from top to bottom. The three most common tools are if statements, for loops, and while loops. Choosing the right one makes code easier to read, debug, and change.

These tools appear in almost every program, from games and apps to data analysis and simulations.

An if statement is best when the program needs to make a decision once based on a condition. A for loop is best when the number of repetitions is known or when you are moving through a sequence such as a list, string, or range of numbers. A while loop is best when repetition should continue until a condition changes, especially when you do not know the number of repeats in advance.

Good programmers choose the structure that matches the logic of the problem, not just the first one that works.

Understanding Loops and Control Flow

A condition is a small test that produces one of two results, true or false. The program uses that result to select a path. Conditions often compare values, but they can test more than numbers.

A login program can check whether a password matches. A game can check whether a player has any lives left. An online shop can check whether a basket is empty.

Clear conditions make code easier to trust. Names such as is_logged_in or has_finished_level show what a condition means without forcing a reader to decode every detail.

A loop is useful because computers are good at repeating careful steps without losing count. In a for loop, the changing loop variable gives each repeat a different item or position. A program that totals test scores can visit each score once.

A drawing program can place a row of shapes by using positions in a range. When working with text, a loop can inspect one character at a time to count spaces or find a symbol. Students should trace a short loop by hand.

Write down the variable value on every pass, then note what changes inside the loop. This habit reveals many mistakes quickly.

While loops depend on the program state. State means the values currently stored while the program runs. Consider a simple quiz that keeps asking for an answer until the user enters the correct word.

Each attempt changes the state because new input is stored. A simulation can keep moving an object while its height remains above zero. In these cases, the code inside the loop must move the situation toward stopping.

It may update a counter, read fresh input, remove an item, or change a flag. If that update is missing or happens in the wrong place, the condition can stay true forever. Infinite loops can freeze a program or make it use large amounts of processing time.

Control structures can be combined, though nesting them too deeply makes code hard to follow. A game might use a loop for each player, then use an if statement to award points when that player reaches a target. A data program might skip missing values inside a loop before doing a calculation.

Pay close attention to where code is indented, since indentation shows which statements belong to a decision or loop in Python. Watch for off by one errors when counting. These happen when code starts one step too early, stops one step too late, or misses the final item.

Test boundary cases such as an empty list, one item, zero attempts, and the exact limit value. Such cases expose weak control flow before it affects real users.

Key Facts

  • Use if when code should run only when a condition is true.
  • Use for when you know how many times to repeat or when iterating through a collection.
  • Use while when repetition depends on a condition that may change during execution.
  • A loop condition must eventually become false, or the loop may run forever.
  • for i in range(n) runs n times in Python, with i taking values 0 through n - 1.
  • Boolean conditions evaluate to True or False, such as x > 5 or name == 'Ada'.

Vocabulary

Control flow
Control flow is the order in which a program's statements are executed.
Condition
A condition is an expression that evaluates to True or False.
If statement
An if statement runs a block of code only when its condition is true.
For loop
A for loop repeats a block of code for each item in a sequence or for a fixed number of steps.
While loop
A while loop repeats a block of code as long as its condition remains true.

Common Mistakes to Avoid

  • Using if when repeated action is needed is wrong because if checks a condition only once. Use a loop when the same block must run multiple times.
  • Using while when the repeat count is known can make code harder to read. A for loop is usually clearer for fixed counts or list traversal.
  • Forgetting to update the variable in a while loop can create an infinite loop. Make sure something inside the loop moves the condition toward False.
  • Confusing = with == in conditions is wrong in many languages because = assigns a value while == compares two values. Use the comparison operator when testing equality.

Practice Questions

  1. 1 A program must print the numbers 1 through 20. Which control flow tool should it use, and how many times will the loop body run?
  2. 2 A password program keeps asking the user to enter a password until the correct password is typed. Should this use if, for, or while, and why?
  3. 3 You are writing code that gives a student a bonus message only if their score is at least 90, then continues with the rest of the program. Which control flow tool is most appropriate, and why is a loop unnecessary?