Programming Fundamentals · Free lesson
Read and trace a simple program
A courier collects parcels from your dispatch desk. Your job is to check the number on the handover slip. You can predict what the program will print with a pencil and four lines of Python.
Follow one value through the pickup
ready = 18
collected = 7
ready = ready - collected
print(ready)
Read one line at a time. The first line stores 18 under the name ready. The second stores 7 under collected. On the third line, Python works out the right-hand side first. It looks up the current values, subtracts 7 from 18, then stores 11 back under ready. The last line prints 11.
That process is called tracing. Each time a line assigns a value to a name, cross out the old value and write down its replacement.
Try a second pickup
On Friday, 15 parcels are ready. The slip needs both the starting count and the count after the courier leaves. Before opening the answer, predict the two numbers this version will print, in order.
ready = 15
on_slip = ready
ready = ready - 4
print(on_slip)
print(ready)
Check my prediction
The program prints 15 and then 11, on separate lines. When Python runs on_slip = ready, the number stored under ready is 15. The next assignment changes ready. The number stored under on_slip is still 15.
Change the order
Move on_slip = ready one line down, just after the subtraction. Keep both print lines where they are. Which count would the dispatch team lose from its slip?
See what changes
Both lines now print 11. The program only saves on_slip after four parcels have left, so the slip loses the original count of 15. To keep a starting value for a report, save it before the first update.
Continue with Programming Fundamentals
The full course includes written lessons, practice tasks and assessments. Open the course to see the outline and access options.
Explore the full course