Beginner Python: the code gets short, the step-by-step tracing never does

This companion walks through the four opening Python lectures of the course UFUG 1601: expressions and variables, for loops, conditionals, and functions. It is written for two readers at once: the instructor or TA preparing these lectures for first-year students with no prior programming, and the complete beginner following along. Every term is defined in plain English the first time it appears, and every claim about what Python does can be checked against the official documentation or a live trace.

Where does this unit sit? A running Python program is a list of instructions the computer executes one after another, like a recipe. Allen Downey's open textbook Think Python opens its first chapters with exactly this framing, programming as a way of thinking, and the course estimates roughly 20 hours of study from zero. Think Python

One habit matters more than any single rule in this unit: predict what a program prints before you run it. It is the fastest way to find where your mental model of the machine is wrong, and every chapter here builds around it.

1. What does Python actually do when you type an expression?

The interpreter is a calculator that shows its work

The first lecture opens with a metaphor the official Python tutorial uses verbatim: the interpreter acts as a simple calculator. An interpreter is a program that reads what you type, works out what it means, and immediately does it. Run python in a terminal and you get an interactive session: type an expression, and the interpreter echoes the value back. Anything that evaluates to a value is an expression: 5, 3 + 4, 44 / 2, 2 ** 3. Python Tutorial

The deck's warm-up makes the chapter's key point with two expressions:

2 + 3 * 4
(2 + 3) * 4

The first is 14, the second is 20. Same numbers, same operators, different answers, because Python evaluates from the inside out and operator precedence decides what counts as inside: multiplication binds tighter than addition, so 2 + 3 * 4 means 2 + (3 * 4). Parentheses override precedence and say explicitly what to compute first. Two warnings in the same family: division always returns a float, so 8 / 5 is 1.6, never 1; and the power operator ** binds tighter than the unary minus on its left, so -3 ** 2 is -(3 ** 2), which is -9, while (-3) ** 2 is 9. When in doubt, write the parentheses. Python Tutorial

Watch one expression dissolve into its value

The deck's signature example is the temperature formula (72 - 32) / 9.0 * 5. Python unwraps it from the inside out: innermost parentheses first, then left to right among operators of equal precedence.

Now compare (72 - 32) / (9.0 * 5). The second pair of parentheses changes the order: the machine computes 9.0 * 5 = 45.0 first, then 40 / 45.0, about 0.888. Two valid expressions, two different answers, no bug involved: that is what an ordered, step-by-step evaluation means, and it is exactly why parentheses are not decoration.

The assignment that prints nothing

One expression-like thing behaves differently in the interpreter, and the deck shows it in a real session. An assignment such as x = 2 is not an expression; it produces no value to echo. The interpreter runs it silently, and you see nothing.

A screenshot of a Python interactive shell session

Caption: The deck's own screenshot of an interactive Python session. Typing x = 2 prints nothing, while typing x echoes 2 and x + y echoes 6. Assignments are silent; expressions show their values. The banner shows Python 3.9.12, the version the deck was captured with.

That silence raises the chapter's handoff question, which the next lecture answers: if x = 2 stores something but shows nothing, what exactly does it store, and what happens when the same name is used again?

2. What does x = 5 store, and why doesn't y = x change when x does?

Assignment is evaluate-then-store, not equality

In algebra, x = 5 asserts a permanent truth. In Python, the equals sign is an instruction, not a promise: evaluate everything on the right-hand side into a value, then store that value under the name on the left. Nothing else happens, and no result is displayed. The assignment never reaches back to touch anything computed earlier. Python Tutorial

The formal word for this is binding: names refer to objects, and an assignment introduces a binding from a name to a value at this moment. Execution Model

The deck exercises this with a ten-line program worth tracing by hand:

x = 2
print(x)
y = x
print(y)
z = x + 1
print(z)
x = 5
print(x)
print(y)
print(z)

After y = x, y holds 2. After z = x + 1, z holds 3. Then x = 5 rebinds x. The question that decides whether you understand assignment is what the next two lines print: y still prints 2, and z still prints 3, because rebinding moves only x's label; earlier values are left alone. The printed output is 2 2 3 5 2 3.

Seeing a rebind happen

The deck points the class to Python Tutor (pythontutor.com), a free web tool that runs a program step by step and draws the computer's memory as it goes. The screenshot below is the deck's own trace, captured right after x = 5 executes.

Python Tutor visualizing the variable trace program

Caption: Python Tutor at step 8 of 10 on the deck's variable-trace program. The frames panel shows a single Global frame with x → 5, y → 2, z → 3, and the print box shows the values printed so far: 2, 2, 3. When line 7 rebinds x to 5, the bindings for y and z do not move. The green and red arrows mark the line that just ran and the one that runs next; those colors are a Python Tutor convention, not a Python feature. Python Tutor

The habit to hand the class: when you are unsure what a short program prints, run it in Python Tutor and step forward one statement at a time. This "watch it run" tool carries the whole unit.

Names should explain the data, and types have rules

Assignment only works if the name is legal, and a legal name is not the same as a good name. Python rejects names that start with a digit (2students), contain a hyphen (student-name), or collide with keywords (class). The style authority is PEP 8: function and variable names are lowercase with words separated by underscores, and the single letters l, O, and I are banned because they look like digits. PEP 8

GoodWhy
student_name = "Alice"lowercase with underscores
temperature_c = 25descriptive, not t
radius = 5; area = 3.14 * radius ** 2meaningful names beat a = 3.14 * 5 ** 2
course_2_score = 90digits allowed inside a name, not at the start

Values come in four basic types: int (whole numbers, exact arithmetic), float (real numbers, approximate arithmetic), str (text, like "I love Python"), and bool (just True and False). Types matter because operators behave differently on different types: 3 + 4 is 7, 3 + 4.0 is 7.0, "3" + "4" is the string "34", but 3 + "4" raises an error, because Python refuses to guess whether you meant addition or concatenation. Conversion functions make the mixing explicit: int(15.5) is 15, float(15) is 15.0, str(3) + "4" is "34". The deck's moral is exactly right: Python sometimes tells you when what you wrote makes no sense, and that error message is a feature, not a bug.

Self-check before running:

x = 5
y = x + 2
x = 10
z = x + y
print(x, y, z)

The answer is 10 7 17: y was computed from the old x (5 + 2) before x became 10, and z uses the new x with that y. So: a name is a label attached to a value at one moment; the machine evaluates the right side now, stores it, and moves on, and earlier labels stay untouched, which is why tracing is the only way to know what a short program prints. The next lecture's question: one value per name is fine, but what if five temperatures all need the same computation?

3. Five pasted blocks or one for loop: what changes, and what doesn't?

From copy-paste pain to one recipe

The second lecture starts from a real annoyance. Converting five Fahrenheit values to Centigrade means pasting the same two lines five times, changing the input each time:

fahr = 30
cent = (fahr - 32) / 9.0 * 5
print(fahr, cent)
fahr = 40
cent = (fahr - 32) / 9.0 * 5
print(fahr, cent)
# ... and so on for 50, 60, 70

Copy-paste works, but it costs you: it is error prone (paste in the wrong place, change the wrong value), it hides bugs (a wrong formula must be fixed in five places), and it hides meaning (a reader cannot tell at a glance that all five blocks are the same computation). The for loop exists precisely to let you write the body once and let the machine run it once per item: the official tutorial says it iterates over the items of any sequence, a list or a string, in the order they appear. Python Tutorial

for fahr in [30, 40, 50, 60, 70]:
    cent = (fahr - 32) / 9.0 * 5
    print(fahr, cent)

print("All done")

Read the header like an assignment: for each item in this list, in order, bind the loop variable fahr to that item, then run the body. The colon after the sequence is required, and the body is identified purely by indentation. A statement back at the left margin, like print("All done"), runs exactly once, after the loop finishes. In the language reference's vocabulary, the for-loop header is itself a name-binding operation, which is why the loop variable takes each item in turn. Execution Model

What changes, and what never changes

The loop writes the body once, but the machine still executes it once per item, with five different values of fahr. That is the "what changes and what doesn't" of the chapter title: the source shrinks from 20 lines to 5, and the step-by-step execution stays exactly as long as it always was.

The deck's reliable trick for seeing this is the transformation approach: rewrite the loop by hand as five unrolled blocks, one per item (f = 30, body; f = 40, body; and so on). You now have code you already know how to trace, and you can see with your own eyes that the body runs five times.

The sequence can be a list or a string (for char in "happy": prints one character per line), or a range. The range function says "count from here to there" without typing a list, and its rule is the source of most off-by-one bugs in this unit: the start is included, the stop is excluded. Python Tutorial

CallYieldsRead as
range(5)[0, 1, 2, 3, 4]zero up to but not including five
range(1, 5)[1, 2, 3, 4]one inclusive, five exclusive
range(1, 10, 2)[1, 3, 5, 7, 9]step of 2
range(5, 1, -1)[5, 4, 3, 2]step can be negative

Accumulation, and loops inside loops

Most real loops do not just print; they build one answer out of many items. The mental model is a three-line recipe: start with a correct result for an empty sequence, update it inside the loop, use it after the loop.

result = 0
for element in [2, 4, 6]:
    result = result + element
print(result)

The same shape with a different starting value and operation gives a sum (result = 0), a product (result = 1), or a maximum (start from mylist[0] and update with max). The body of a loop can itself contain a loop; then the whole inner loop completes for each outer item. Trace a nested loop the same way: unroll the outer loop first, then unroll each inner loop. One trap worth warning the class about: the loop variable still exists after the loop, holding its last value, and reusing it inside a nested loop overwrites the outer one, so do not reuse i as both variables.

That is the chapter's takeaway: the loop writes the body once while the machine still runs it once per item; indentation decides what is inside the repetition, and range's stop-exclusive rule is where off-by-one bugs are born. The next question: a loop repeats every statement in its body, but what if a program should run some statements and skip others, depending on the data?

4. How does a program choose a path, and why does the order of the ifs matter?

A Boolean test picks one of two branches

The third lecture starts with a computation that needs a decision: absolute value. If the value is negative, negate it; otherwise, keep it. Python has a type for exactly this yes-or-no question, the Boolean: comparisons like temp > 32 and 22 == 4 evaluate to True or False, and not, and, or combine them (3 < 4 and 5 < 6 is True). The if statement tests a Boolean condition and runs one of two bodies:

val = -10
if val < 0:
    result = -val
else:
    result = val
print(result)

Indentation is significant here exactly as for loops: the statements indented under if run only when the condition is True, those under else only when it is False, and anything at the left margin runs regardless. The else is optional. And because result is assigned in both branches, it is guaranteed to have a value whichever path ran.

An elif chain: exactly one branch runs

Three-way decisions need more branches, and the deck builds the canonical example from a height scale: the simplified atmosphere, where below 20 km is the troposphere, 20 to 50 the stratosphere, 50 to 100 the mesosphere, and above 100 space. The clean version is the elif chain:

height = 72
if height > 100:
    print("space")
elif height > 50:
    print("mesosphere")
elif height > 20:
    print("stratosphere")
else:
    print("troposphere")

Exactly one branch executes: the first whose condition is true, or the else branch if none is. The official tutorial calls this shape a substitute for the switch or case statements found in other languages; if your students know another language, say it plainly: Python has no switch, and this is the idiomatic replacement. Python Tutorial

Each test is only reached when every earlier one was false. That waterfall picture explains the next two warnings.

Why order matters, and why separate ifs are not a chain

Reorder the chain so a broader condition is tested first and it breaks. Put height > 20 first, and for height 72 the machine prints "stratosphere" and never reaches the later conditions, because the first true branch wins:

if height > 20:        # broken: catches 72 first
    print("stratosphere")
elif height > 50:
    print("mesosphere")
elif height > 100:
    print("space")

The rule of thumb: put the narrowest, most restrictive condition first and the broadest one last, because a broad condition placed first swallows every narrower case below it.

A row of separate if statements is not a chain either. The deck's trap example writes three independent ifs: for height 72, the first if is false (not space), the second if is true and prints "mesosphere", the third if is also true and prints "stratosphere", and the else attaches only to the last if, so it never runs because that condition is true. Two lines printed — mesosphere and stratosphere — which an elif chain could never do. Each condition is checked independently, and that is the difference: a chain chooses one path, a row of ifs can take several.

One more property worth showing with the deck's speed/fine example: only the branch that runs is evaluated. In if speed <= limit: print("Good job!") else: print("You owe $", (speed - limit) * fine), the name fine is only looked up when the else branch actually runs. If fine is never defined anywhere, the program crashes only for speeding drivers, not for law-abiding ones.

So: a condition is tested once, in order, and the first true branch wins; the other branches are never even evaluated, which is why you order from the narrowest condition to the broadest and why separate ifs are not a substitute. The next question: a computation can now branch and loop, but what if the same computation is needed in several places, or with different inputs?

5. What is the difference between printing an answer and returning it?

Packaging a computation under a name

The fourth lecture introduces functions, and the deck frames them as machines: you give one input, it produces a result. The definition form def dbl_plus(x): return 2 * x + 1 does three things: it names the computation (dbl_plus), declares its input (x, the formal parameter), and says what value comes out (return 2 * x + 1). The point is reuse and generalization: write the recipe once, then call it with different arguments.

The official tutorial describes what happens at a call: a function call introduces its arguments into the function's own local symbol table, and executing the function creates a fresh structure that holds that function's variables. Python Tutorial

A call, step by step

When Python runs square(3 + 4), it follows five steps: evaluate the argument at the call site (7); bind it to the formal parameter as a new variable; run the body statement by statement; at the return statement, send the value back and remove the call's frame; and the whole call expression now has that value. The deck's slide-38 list calls the frame a stack frame, and the language reference confirms the core idea: a code block is executed in an execution frame, and each function body is its own block with its own bindings. Execution Model

The parameter is a new variable, not a reuse of any variable with the same name elsewhere, so a formal parameter disappears when the call ends. This is the frame picture, and Python Tutor renders it exactly, as the deck's hypotenuse example shows: hypotenuse(3, 4) calls square(x), and at that moment two calls are alive at once, each with its own frame.

Python Tutor visualizing the hypotenuse function call

Caption: Python Tutor at step 8 of 13 while running hypotenuse(3, 4). The frames panel shows three frames nested at once: the Global frame (with math, square, and hypotenuse bound to their objects), the hypotenuse frame holding x=3, y=4, and the square frame holding z=3, with the line return z * z highlighted. This is the frame mental model: every active call owns a fresh little world of local variables, and frames coexist until each call returns. Python Tutor

That picture is also why locals are local: a variable created inside a function, like result inside cent_to_fahr, exists only while the function runs, so the main program cannot read it. Lookup follows the same nesting: check the local frame first, then the global frame, and a local name shadows a global one with the same name, which the deck advises avoiding.

Returning a value versus printing one

The signature confusion of this lecture is return versus print. Printing writes text to the screen; returning hands a value back to whoever called the function, ready to be used in a larger expression. A function with no return statement still returns something: the official tutorial says it returns a value, albeit a rather boring one, called None. Python Tutorial

The deck's puzzle print(cent_to_fahr(20)) where cent_to_fahr prints instead of returning is the classic trap: it prints the computed value, and then the outer print outputs None, because the call itself returned nothing. Two lines appear, and the second one is a puzzle for the whole class.

Documenting the recipe

A function should say what it does. The deck pairs a docstring with assert tests, the standard shape being a triple-quoted string right after def, describing inputs and return value, plus asserts that check the function on known examples. PEP 257 defines the conventions: one-line docstrings should be a short imperative phrase ending with a period, with the closing quotes on the same line. PEP 257

def fahr_to_cent(fahr):
    """Return the Celsius value for a Fahrenheit input."""
    return (fahr - 32) / 9.0 * 5

assert fahr_to_cent(32) == 0
assert fahr_to_cent(212) == 100

The design recipe the deck recommends is worth keeping on the board: wishful thinking (write the program as if the function existed), write a specification, write tests, then write the body. This is also where Python Tutor earns its keep: research has documented that tens of millions of learners across more than 180 countries have used it since 2010, and it was designed precisely to imitate what an instructor draws on the blackboard. Guo UIST 2021

So: a function call opens a fresh local world, a frame; parameters are new variables, locals die when the call ends, and a value that is printed is not returned. The frame picture is the difference. The final question: can a beginner keep the tracing habit when one program combines all four ideas at once?

6. One program, all four ideas: what breaks, and how do you catch it?

The master habit: predict before you run

Every lecture ended with predict-the-output puzzles, and they work because predicting forces your mental model to commit before it gets corrected. The unit's practice block gathers them: trace x = 5; y = x + 2; x = 10; z = x + y to 10 7 17; predict print(2 < 7 or 3 > 12) (True, since the first comparison is true); wonder about for i in []: print(i) (an empty sequence runs the body zero times, so nothing prints); and puzzle over print(i) after a loop (the loop variable survives with its last value). Think Python's chapter exercises are the natural homework source at exactly this difficulty: open-access, short code samples, glossary, exercises. Think Python

The cumulative program

Here is the unit's final exam, the deck's own function-in-a-loop example shaped to also exercise a conditional. Predict each printed line before running it:

def c_to_f(c):
    print("c_to_f")
    return c / 5.0 * 9 + 32

def make_message(temp):
    print("make_message")
    if temp > 0:
        sign = "above freezing"
    else:
        sign = "at or below freezing"
    return "The temperature is " + str(temp) + ": " + sign

for tempc in [-40, 0, 35]:
    tempf = c_to_f(tempc)
    message = make_message(tempf)
    print(message)

For tempc = -40 the machine calls c_to_f (printing "c_to_f"), gets -40.0, calls make_message (printing "make_message"), tests the conditional, and prints the message; then the loop moves on to 0, then 35. Every printed line is traceable, and every part of the program exercises a feature from the unit:

Part of the programFeature it exercises
tempf = c_to_f(tempc)function call, assignment, variables
return c / 5.0 * 9 + 32expressions, float division, return
if temp > 0: inside make_messageconditional, branch selection
str(temp) inside the returntype conversion, string concatenation
for tempc in [-40, 0, 35]:for loop over a list, loop variable

Run it in Python Tutor and step through: you should see exactly the frames, branches, and prints you predicted. Python Tutor

Referee, not oracle

Python Tutor is the referee here, not because it thinks for the student, but because it makes every step visible and checkable. Use it the way the deck does: predict, run, compare, and find which of your predictions was wrong and why. The tool has a peer-reviewed record to back this recommendation: an academic retrospective documents its decade of service and its design guidelines, and its own site reports tens of millions of users and hundreds of millions of visualizations (the exact figures drift over time, so teach the order of magnitude, not the precise number). Guo UIST 2021

The common beginner pitfalls across the whole unit cluster in five places: mixed types (3 + "4"); off-by-one ranges (range(5) never yields 5); loop variables re-used or read after the loop; print where return was needed, producing None; and forgetting that a string from input needs conversion before arithmetic. Each one shows up in the predict-the-output habit far earlier than in a debugger.

So the unit closes where it began: predicting the output before running it is the fastest way to find a gap in the mental model. The code a beginner writes gets shorter at every step, one loop instead of five pasted blocks, one elif chain instead of hand-picked cases, one function instead of repeated code, but the machine keeps executing one statement at a time, and the step-by-step tracing never does.

参考文献

本专题引用的核心资料如下,建议深入学习时阅读原文:

  1. The Python Tutorial (Python 3.14.7 documentation) — https://docs.python.org/3/tutorial/index.html
  2. 4. Execution model — Python Language Reference (3.14.7) — https://docs.python.org/3/reference/executionmodel.html
  3. PEP 8 – Style Guide for Python Code — https://peps.python.org/pep-0008/
  4. Think Python (3rd edition, Allen B. Downey, O'Reilly 2024) — https://allendowney.github.io/ThinkPython/
  5. PEP 257 – Docstring Conventions — https://peps.python.org/pep-0257/
  6. Python Tutor (pythontutor.com, live visualization tool) — https://pythontutor.com/
  7. Ten Million Users and Ten Years Later: Python Tutor's Design Guidelines (Guo, UIST 2021) — https://dl.acm.org/doi/10.1145/3472749.3474819
Beginner Python: the code gets short, the step-by-step tracing never does