What happens when code runs?
Follow instructions, values, and decisions from input to output.
Instructions and state
A program describes operations to perform. At any given moment it has a state: the values it is holding and its current position in the instructions. As instructions execute, values may change and control may move to a different part of the program.
How it works
For the sample, write the state after each line. It starts with score 4. The update gives score 7. The comparison asks a yes-or-no question about that new value, so the program selects the corresponding message. The same method works when a program has more complicated state.
Predict the output
Imagine the program starts with a score of 4. It adds 3, tests whether the new score is at least 6, and prints a message. The decision examines 7 because the update has already happened. When tracing a program, record the new value immediately after each assignment.
Try a different input
Start with a score of 1 and do the same steps on paper. The added 3 produces 4, so the condition is false. A good test set includes an input for each branch and the exact value at the boundary.
Code example
score = 4
score = score + 3
if score >= 6:
print("Level up")
else:
print("Keep going")Check your understanding
The program adds 3 to the input score before comparing it with 6. Predict the exact message.
See the example and explanation
- At the threshold
- Given
3 - Answer
Level up - Below the threshold
- Given
2 - Answer
Keep going
A starting score of 3 becomes 6. Equality satisfies greater-than-or-equal. A starting score of 2 becomes 5, so the else branch prints Keep going.