Step 1 โ Spot the Inputs and Outputs
Scan for input(), function parameters, and print(). This tells you what the code consumes and produces.
Step 2 โ Find the Loops
Loops contain most of the logic. Ask: how many times does it run? What variable changes each iteration?
Step 3 โ Identify the State
Which variables accumulate information (counters, totals, result lists)? These are where output usually comes from.
Step 4 โ Trace One Iteration
Run through the first iteration with concrete values. Write down the state after each line. If you can do iteration 1 and 2, you understand the code.
Example
def mystery(lst):
best, best_i = lst[0], 0
for i, x in enumerate(lst):
if x > best:
best, best_i = x, i
return best_i
Inputs: a list. Output: an index. Loop: over each element with index. State: best, best_i. Conclusion: returns the index of the maximum.
Practise this on PyForm โ free
PyForm runs Python in your browser with an AI tutor trained for HKDSE. No install, no credit card.
Open PyForm โ