STEM & EngineeringTechnology & EngineeringCoding and computational thinkingAbout 10 minutes

Variables, if statements, and loops

See how programs remember values, make decisions, repeat useful work, and stop at the intended time.

Three tools, three jobs

A variable gives a name to a value that a program can read or change. For example, a variable named score might begin at 0 and increase whenever a player earns a point. A clear name makes the value’s purpose easier to understand.

A conditional checks a true-or-false condition and chooses which instructions run. A loop repeats a block of instructions for a known number of times or while a condition remains true. These ideas work across programming languages even when the exact syntax changes.

Trace the changing state

Program state means the current values stored while a program runs. To trace a program, move through one instruction at a time and record each variable after it changes. A small table with the loop number, condition result, and current values can make the logic visible.

A condition-controlled loop needs a way to reach its stopping point. If the values used by its condition never change in the needed direction, the loop may continue forever. Testing the first pass, the last expected pass, and an edge case can reveal that problem.

Remember these ideas

Key ideas

  • A variable names a value that a program can read or update.
  • A conditional runs different instructions according to a true-or-false test.
  • A loop repeats instructions while its repetition rule allows.
  • Tracing shows how program state changes and whether a loop can stop.

Make the reasoning visible

Trace a point counter

  1. 1

    Begin with points = 0 and token values [4, 7, 3]. For each token, if token ≥ 5, add 2 to points; otherwise add 1.

  2. 2

    The first token is 4. The condition token ≥ 5 is false, so add 1 and change points to 1.

  3. 3

    The second token is 7. The condition is true, so add 2 and change points to 3.

  4. 4

    The final token is 3. The condition is false, so add 1. The loop ends and the program outputs 4.

Try the next step

Trace a filtered total

A program sets total = 0, then loops through [3, 8, 5]. For each number, it adds the number to total only when number > 5. What does the program output?

How would the output change if the condition were number ≥ 5, and why?

Check your understanding

In the loop “count = 1; while count < 5: display count; count = count + 1,” why is the final instruction important?

In the loop “count = 1; while count < 5: display count; count = count + 1,” why is the final instruction important?

Student explanations

Student contributions, separate from the lesson above
Checking for student explanations…