Introduction to Programming II

State, expressions, and scope

Paolo Rota

September 18, 2026

Recap

Last time we built the notional machine: a finger moving down the lines, some memory, and a screen.

Today we look inside two of those pieces:

  • State — what memory holds, and how it changes over time.
  • Scope — the rules for which names are visible where.

Concepts again — but today every one of them gets checked against the real machine. Keep the REPL open. Syntax details come in Lecture 3.

State

Rule 3 — the machine remembers

The machine’s memory is a set of labelled boxes. A label is a name; the box holds a value.

x = 5

Read this as an instruction:

“Make a box labelled x and put the value 5 in it.”

The state of a program is the collection of all its name → value bindings at a given moment. Running the program is nothing but changing the state, step by step.

x is not "x"

In Lecture 1 the quotes marked the data print acts on. They still do. Quotes mean “this text, exactly as written”. No quotes means “go to the box with this label and take out what is inside”.

x = 5
print("x")
print(x)
x
5
name = "Ada"
print("Hello, name")
print("Hello,", name)
Hello, name
Hello, Ada

"x" is a value: the one-letter text x, the same wherever it appears. x is a name: a label on a box. The machine never prints a label — it opens the box and prints what it finds.

= puts a value in a box

x = 5      # put 5 in box x
x = x + 1  # read x (5), add 1, put the result (6) back in x
print(x)
6

The line x = x + 1 is nonsense as algebra but perfectly clear as an instruction:

Step Action State after
1 x = 5 x → 5
2 evaluate x + 1 → 6, store in x x → 6

Later we meet ==, which tests equality. = changes state; == asks a question.

Tracing state

Trace tables now get a state column:

a = 2
b = 3
a = b
b = 10
print(a, b)
3 10
Step Action a b
1 a = 2 2 —
2 b = 3 2 3
3 a = b 3 3
4 b = 10 3 10

After step 3, a is 3. Changing b afterwards does not change a: each box holds its own value.

Values, expressions, statements

Three words you’ll use constantly

  • A value is a piece of data: 5, "hello", True.
  • An expression is anything the machine can evaluate to a value: 2 + 2, x, len("cat").
  • A statement is an instruction that does something: x = 5, print(x).

Rough test: if you can put it on the right of an =, it’s an expression. If it stands alone and acts, it’s a statement.

Evaluation: expressions become values

The machine evaluates an expression down to a single value before using it.

total = 2 + 3 * 4
print(total)
14

Evaluation of the right-hand side:

  1. 3 * 4 → 12
  2. 2 + 12 → 14
  3. store 14 in total

Multiplication before addition — the machine follows the usual arithmetic precedence. When in doubt, add parentheses.

Expressions can contain names

price = 10
qty = 3
cost = price * qty
print(cost)
30

To evaluate price * qty, the machine first looks up each name in the current state (price → 10, qty → 3), then multiplies.

If a name has no box yet, the lookup fails:

total = cost - discount
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[7], line 1
----> 1 total = cost - discount

NameError: name 'discount' is not defined

The value decides what + does

Same operator, different values in the boxes. Predict each output before the click.

print(2 + 2)
print("2" + "2")
4
22
print("2" * 3)
222
print("2" + 2)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[10], line 1
----> 1 print("2" + 2)

TypeError: can only concatenate str (not "int") to str

Every value has a type: 2 is a number, "2" is a piece of text. The machine looks at the types first, then decides what + means — add, or glue together. Mix them and it refuses: a TypeError — a third error name, to put beside the two we already met, SyntaxError and NameError. Next lecture is all about types.

Scope

Why “where is this name visible?” matters

As programs grow, we reuse short names like x, i, result. If every name were visible everywhere, they’d collide constantly.

Scope is the region of a program where a given name is visible and usable. A name created in one scope may be invisible in another.

We meet scope properly with functions (Lecture 5), but the idea starts now.

A first look: functions make a new scope

def greet():
    message = "hi"      # 'message' lives INSIDE greet
    print(message)

greet()
print(message)          # ERROR: not visible out here

hi NameError: name ‘message’ is not defined

message exists only inside greet — its local scope. Outside, the name is unknown. This is a feature: the function’s internals stay private.

Local vs global

title = "Course"        # global: visible everywhere below

def show():
    subtitle = "Intro"  # local: visible only inside show()
    print(title)        # can READ the global
    print(subtitle)

show()
print(title)            # fine
print(subtitle)         # NameError
  • Global names: defined at the top level of the file.
  • Local names: defined inside a function, born when it’s called and gone when it returns.

The lookup rule (informal)

When the machine meets a name, it searches scopes inside-out:

  1. the local scope (inside the current function), then
  2. the global scope (the file), then
  3. the built-ins (print, len, …).

First match wins; if none match → NameError.

Scope is just the machine’s rule for resolving a name to a box. Keep it in your notional machine and “why can’t it see my variable?” stops being a mystery.

Why beginners get bitten

def add_tax():
    total = 100 + 20    # this 'total' is LOCAL

add_tax()
print(total)            # NameError — the local total is gone

The function computed total, then returned, and its local scope vanished. To get a value out of a function we must return it — that’s Lecture 5.

What to take away

  1. State = all name→value bindings right now; programs change state.
  2. = assigns (changes state); == tests (asks a question).
  3. Expressions evaluate to values; statements act.
  4. Scope decides which names are visible where — inside-out lookup.

Next: the actual data types that go in those boxes.

Try it now

Which error, if any?

Four short programs, two here and two on the next slide. For each one: does it stop the machine, and with which error? Decide first, then click.

score = 5
print(score + bonus)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[11], line 2
      1 score = 5
----> 2 print(score + bonus)

NameError: name 'bonus' is not defined
print("a" + 5)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[12], line 1
----> 1 print("a" + 5)

TypeError: can only concatenate str (not "int") to str

NameError — score has a box, bonus never got one · TypeError — both values exist, but + cannot join text and a number.

Which error, if any? (2)

print("a" * 5)
aaaaa
Points = 5
print(Points)
print(points)
5
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[14], line 3
      1 Points = 5
      2 print(Points)
----> 3 print(points)

NameError: name 'points' is not defined

In order — NameError (no box called bonus) · TypeError (text plus number) · no error at all, aaaaa · NameError (Points and points are two different labels).

Final state

Without running it, write down the value of every name at the end:

p = 2
q = p + 3
p = q
q = p * 2
p = q - q

Then check with print(p, q).

Solution — p → 2, q → 5, p → 5, q → 10, p → 0. Final: p = 0, q = 10.

Name or text?

What exactly appears on the screen?

fruit = "apple"
print("fruit")
print(fruit)
fruit = "pear"
print("fruit", fruit)
fruit
apple
fruit pear

Solution — fruit · apple · fruit pear. Quotes print the text itself; no quotes prints what is in the box, whatever is in it at that moment.

Count to three

Start from count = 0. Write instructions that leave count holding 3 — without the digit 3 appearing anywhere in your program — printing the value after every step.

Solution — three times count = count + 1, each followed by print(count). The ban on writing 3 is what forces you to change state step by step instead of jumping to the answer.

Where does it break?

Predict the output line by line, then run it:

total = 10

def show():
    bonus = 5
    print(total)
    print(bonus)

show()
print(bonus)

Solution — 10, then 5, then NameError: name 'bonus' is not defined. Inside show, total is not local, so the lookup moves outward and finds it. bonus is local: when the call ends its box is gone.

Take home

Exercise 1 — Expression or statement?

For each line, say whether it is an expression or a statement, and if it’s an expression, what value it evaluates to (assume x = 3).

x + 7
print(x)
x = x + 7
len("banana")
"a" * x

Solution — x + 7 expression → 10 · print(x) statement (acts: displays 3) · x = x + 7 statement (changes state) · len("banana") expression → 6 · "a" * x expression → "aaa".

Exercise 2 — Swap two boxes

Given a = "left" and b = "right", write instructions so that afterwards a holds "right" and b holds "left".

Hint: if you just write a = b then b = a, trace the state — why does it fail? Introduce a third box to fix it. (Later you’ll learn Python’s one-line trick, but do it the explicit way first.)

Solution — after a = b both boxes hold "right"; "left" is lost before b = a runs. Park it first: tmp = a · a = b · b = tmp → a = "right", b = "left".

Questions?