Trace a Python expression
Keep a steady rhythm through each period. · 133 words
A variable names a value. In Python, the line score = 3 assigns the number three to the name score. The expression score * 2 then evaluates to six. Evaluating the expression alone leaves score at three. Assign its result to score to change the stored value.
Keep two columns on paper. In the left column put the line being evaluated; in the right put the value currently associated with the name. For score = score * 2, Python first evaluates the expression on the right using the old value. It then binds the name on the left to the result. Starting at three, performing that assignment twice leaves twelve. This simple tracing method becomes especially useful when a score is updated inside a loop and intermediate values disappear from the final output.
Check your recall
What is score after evaluating score * 2 without assignment?
Check your answer
It is still three. The multiplication produced a result without assigning it.
Sources and credits
Original KeyTouch lesson. Background reading · Python Software Foundation · Python tutorial.