Grade by Grade
A. Programming Concepts and Skills · Programming Basics: Data, Decisions and Loops

Variables, Constants and Assignment Statements

A1.1 A1.3 A4.2 A4.4About 70 minutes
Learning goals
  • I can create variables with assignment statements and explain what = means in Python.
  • I can predict the result of a sequence of assignments, including x = x + 1, using a trace table.
  • I can choose meaningful variable names that follow Python's rules and conventions.
  • I can use a named constant for a value that should not change.
  • I can swap the values of two variables.

Words to know

variable
A name that refers to a value stored in memory. The value can change while the program runs.
assignment statement
A statement such as total = 25 that gives a variable a value. The right side is worked out first, then stored under the name on the left.
constant
A named value that is not meant to change, such as HST_RATE = 0.13. In Python, constants are written in UPPER_CASE by convention.
identifier
Any name you create in a program (a variable, constant or function name).
keyword
A word reserved by Python, such as if, for, while, and, True or None. A keyword cannot be used as a variable name.
snake_case
The Python convention for variable names: lower-case words joined by underscores, such as snow_days.
trace table
A table that records the value of each variable after each line runs. Used to predict and check a program by hand.

Keeping score

At a hockey game, the scoreboard shows the score, the period and the time left. The score changes during the game. The number of periods in a regular game (3) does not. A program needs to remember values like these. It does that with variables and constants.

Assignment: giving a name to a value

An assignment statement has a name on the left, an equals sign, and a value or expression on the right:

  • snow_days = 4
  • city = "Thunder Bay"
  • temperature = -12.5

Read = as "gets" or "is assigned", not "equals". snow_days = 4 means "the name snow_days gets the value 4".

Python always does an assignment in two steps:

  1. Work out the right side completely, using the current values of any variables in it.
  2. Store the result under the name on the left (create the variable if it is new, or replace its old value).

That is why count = count + 1 makes sense in Python even though it is impossible in math: take the old value of count, add 1, and make that the new value of count.

score = 2score2the name score nowrefers to the value 2score = score + 1score231. work out the right side:2 + 1 is 32. move the name to 3
A variable is a name attached to a value. In score = score + 1, Python first works out the right side using the old value (2 + 1 = 3), then attaches the name to the new value. The old value is no longer used.
snow_days = 4
print(snow_days)
snow_days = snow_days + 1
print(snow_days)
city = "Thunder Bay"
print("Snow days in", city, "so far:", snow_days)

A variable keeps its value until a new assignment changes it. Output, line by line: 4 | 5 | Snow days in Thunder Bay so far: 5

Using a variable before it exists

A variable must be assigned before you use it. If line 1 of a program is print(total), Python stops with NameError: name 'total' is not defined. This is also what happens if you spell a variable two different ways, such as total and Total: Python is case-sensitive, so those are two different names.

Rules and conventions for names

Rules (Python enforces these; breaking one is a syntax error):

  • Use only letters, digits and the underscore _.
  • Do not start with a digit: 2nd_place is not allowed, second_place is.
  • No spaces: snow days is not allowed.
  • Do not use a keyword such as if, else, for, while, and, or, not, True, False or None.

Conventions (professional habits; Python does not force them, but your teacher and any employer will expect them):

  • Use meaningful names: price_per_kg, not p or x2.
  • Use snake_case for variables: lower-case words joined by underscores.
  • Use UPPER_CASE for constants: HST_RATE, MAX_PLAYERS.
  • Avoid names of built-in functions such as print, input, sum or max. Python allows print = 5, but after that line, print(...) no longer works in that program.

Constants in Python

Many languages can lock a constant so it can never change. Python cannot: HST_RATE = 0.13 is an ordinary variable. Writing the name in UPPER_CASE is a promise to every reader that nobody will change this value while the program runs. Put constants near the top of the program, after the header comment, so they are easy to find and update. If Ontario's HST rate ever changed, you would edit one line instead of hunting for every 0.13.

# Constants
HST_RATE = 0.13 # Ontario HST is 13%
# Price of a winter coat
price = 200
tax = price * HST_RATE
total = price + tax
print("Tax:", tax)
print("Total:", total)

A named constant makes the formula easy to read and easy to update. Output, line by line: Tax: 26.0 | Total: 226.0

Shortcuts: augmented assignment

Changing a variable by itself is so common that Python has short forms:

  • score += 3 means score = score + 3
  • lives -= 1 means lives = lives - 1
  • price *= 2 doubles price
  • share /= 4 means share = share / 4

You can also assign several variables in one line: x, y = 3, 7 sets x to 3 and y to 7.

Worked example

Example 1: A trace table

Trace this program. Record each variable's value after every line, then give the output.

  • a = 6
  • b = a * 2
  • a = a + b
  • b -= 5
  • print(a, b)
  1. Make a table with one column per variable and one row per line.
  2. Line 1: a = 6. b does not exist yet.
  3. Line 2: right side a * 2 = 6 × 2 = 12, so b = 12. (a is still 6.)
  4. Line 3: right side a + b = 6 + 12 = 18, so a = 18.
  5. Line 4: b -= 5 means b = b - 5 = 12 − 5 = 7.
  6. Line 5 prints the current values.

Trace: (a, b) = (6, —), (6, 12), (18, 12), (18, 7). Output: 18 7.

Worked example

Example 2: Swapping two values

a = 5 and b = 8. Write code that swaps them, so a is 8 and b is 5.

  1. A first try, a = b then b = a, fails: after a = b, both are 8, and the 5 is gone. Then b = a makes b 8 too.
  2. Fix: save one value in a temporary variable first: temp = a, then a = b, then b = temp. The diagram below shows each step.
  3. Python also has a one-line swap that you will see in other people's code: a, b = b, a. The right side is worked out completely (8, 5) before either name changes.

temp = a, a = b, b = temp (or a, b = b, a). Now a is 8 and b is 5.

starta5b8temptemp = aa5b8temp5a = ba8b8temp5b = tempa8b5temp5
Swapping two variables with a temporary variable, step by step. Without temp, the line a = b would lose the 5 forever.
Just for fun

A famous programmers' joke, usually credited to Phil Karlton, says there are only two hard things in computer science: cache invalidation and naming things. After you spend five minutes choosing between total_snowfall and snowfall_total, you will understand.

Hands-on activity

Cups and sticky notes

You need: three cups or mugs, three sticky notes (or paper scraps and tape), and two different small items, for example a coin and a button.

  1. Label the cups a, b and temp. Put the coin in a and the button in b. These are your variables and their values.
  2. Try to swap them using only cups a and b, moving one item at a time, and never holding an item in your hand between moves (a cup can hold only one item, just as a variable holds one value). You will find you are stuck.
  3. Now use temp: move a's item into temp, then b's item into a, then temp's item into b. Say each step as a line of code.
  4. On paper, write the three lines of Python for what you just did, then type them into Python with a = "coin" and b = "button", and print a and b to check.

What to look for: the three lines are temp = a, a = b, b = temp, and the output shows button for a and coin for b. One difference from real Python: an assignment copies the reference, so after temp = a, both temp and a refer to the coin. The cups are only a model.

Your turn

1

What is printed?

  • x = 10
  • x = x - 4
  • print(x)
2

What is printed?

  • n = 3
  • m = n
  • n = 7
  • print(m, n)
3

Which names are not allowed in Python? total_cost, 2nd_try, first name, _count, while, Grade11

4

Rewrite with better names, following conventions: a = 5, b = 4.25, c = a * b (it calculates the cost of 5 bus tickets at $4.25 each).

5

Make a trace table and give the output.

  • p = 2
  • q = p + 3
  • p = q * p
  • q += p
  • print(p, q)
6

Write one line using augmented assignment to triple points.

7

Why is it better to write GST_RATE = 0.05 at the top of a program than to type 0.05 in several places?

More practice: warm-up

1

In Python, how should you read x = 5 aloud?

2

By convention, how is a constant's name written?

3

What is printed?

  • lives = 3
  • lives -= 1
  • print(lives)
4

Is Total the same variable as total?

5

Write score += 10 without the shortcut.

More practice: on your own

1

Trace and give the output.

  • a = 1
  • b = 2
  • c = 3
  • a = b + c
  • c = a - b
  • b = c * 2
  • print(a, b, c)
2

This program should show Total: 30 but crashes. Find the error and fix it.

  • subtotal = 30
  • print("Total:", Subtotal)
3

What is printed? Explain.

  • x, y = 4, 9
  • x, y = y, x + y
  • print(x, y)
4

A student writes a = b then b = a to swap a = 1 and b = 2. What are the final values? Why?

5

Write a short program with a constant KM_PER_LAP = 0.4 and a variable laps = 12 that prints the total distance run.

Challenge

1

Swap the values of a and b (both numbers) without a temporary variable and without the a, b = b, a shortcut, using only + and -.

2

Trace and give the output.

  • total = 0
  • total += 5
  • total *= 3
  • total -= total // 2
  • print(total)
3

Three variables a = 1, b = 2, c = 3 must be "rotated" so that a gets b's value, b gets c's value and c gets a's original value. Write the code using one temporary variable.

Check your understanding

Quiz

1.

After x = 4 and then x = x * 3, what is the value of x?

2.

Which variable name follows both Python's rules and its conventions?

3.

a = 7 then b = a then a = 1. What is b?

4.

How does Python show that a value is a constant?

5.

Which line is the same as lives = lives - 1?

6.

Line 1 of a program is print(speed). No other line mentions speed before it. What happens?

For parents and teachers

Big idea: expectations A1.1 (using constants and variables) and A1.3 (assignment statements), with naming conventions (A4.2) and a first look at tracing (A4.4).

How to help: ask your teen to "be the computer": read a short program aloud and keep a trace table on paper, crossing out old values. The cups activity is a good way to see why a swap needs a third place.

Common difficulties:

  • Reading = as "equals". In Python it means "gets". x = x + 1 is not a contradiction.
  • Expecting b = a to link the two variables forever. It only copies the current value (for numbers and strings, which cannot be changed in place).
  • Capital letters: Total and total are different variables.
  • Short, meaningless names like a, x2. Encourage names that say what the value is.