Python usually executes straightforward script statements from top to bottom. Understanding this sequence makes later concepts like conditions and functions much easier.
Understanding the Concept
When a script starts, a name must be assigned before a later statement can use it. Expressions on the right side of assignments are evaluated with the values available at that moment. A later reassignment does not travel back in time to modify output already printed. More advanced programs can branch, loop, and call functions, but this introductory tracing rule is the starting point.
When and Why You Would Use This
Read the example once without running it. Track the value of counter after each assignment and predict what each print displays. Then execute it and check your mental trace.
Practical Example
counter = 2
print("Before:", counter)
counter = counter + 3
print("After:", counter)
Understanding the Example
The first print displays Before: 2. The reassignment computes 2 + 3 and binds 5 to counter. The last print displays After: 5. The first printed line is not retroactively updated.
Example Output
Before: 2
After: 5
Try It Yourself
Insert a third update of counter after the last print and predict how many lines will appear.
Common Beginner Mistakes
- Reading the program bottom-up and missing earlier assignments.
- Treating reassignment as changing previous console output.
- Using a name before its first assignment and getting NameError.
Key Takeaways
- Straightforward script statements run in execution order.
- An assignment changes which value a name refers to from that point forward.
- Trace intermediate values to predict program output.