Python Quest

Track 2 · Lesson 1 of 11

Variables and assignment

Store values under names, change them as a program runs, assign several at once and swap two values safely.

About 25 minFirst steps4 exercisesFree

You will be able to

  • Create a variable with an assignment statement and use it later in the program
  • Reassign a variable, including using its old value to compute the new one
  • Assign several variables in one line with multiple assignment
  • Swap the values of two variables without losing either one

Imagine a café till. During the day it has to remember the price of each drink, how many cups were sold and the running total in the drawer. A program needs the same kind of memory, and in Python that memory comes from variables.

A variable is a name that refers to a value. You create one with an assignment statement: the name, an equals sign, and the value.

price = 14

Read this as "price now refers to 14", not "price equals 14". The = sign is an instruction: work out the value on the right, then attach the name on the left to it. From then on, wherever you write price, Python uses 14.

Storing values and using them later
drink = "Flat white"
price = 14
cups = 3

print(drink)
print("Cups sold:", cups)
print("Takings:", price * cups, "SAR")

Try it: Change cups to 7 and run it again. Only one line changes, but the takings update too.

Line by line:

  1. drink = "Flat white" stores a string under the name drink.
  2. price = 14 and cups = 3 store two numbers.
  3. print(drink) looks up the name and prints the value it refers to. There are no quotes around drink here — with quotes you would print the word drink itself.
  4. price * cups is worked out using the stored values: 14 * 3 is 42.

Using a name before you have assigned it is an error. Python stops with a NameError, because it has no idea what the name refers to:

A name must be assigned before it is used
total = 120
print(totl)

Try it: Fix the spelling of the name in the second line so the program prints 120.

Reassignment

A variable can be given a new value at any time. The old value is forgotten and the name now refers to the new one. Python runs top to bottom, so what a name refers to depends on which line you are at.

The most common pattern uses the variable's own value on the right-hand side:

stock = stock - 5

Python works out the right side first (the current stock minus 5) and only then moves the name stock to that result.

A stock count changing over a day
stock = 40
print("Opening stock:", stock)

stock = stock - 12   # a customer buys 12
print("After sale:", stock)

stock = stock + 25   # a delivery arrives
print("After delivery:", stock)

Try it: Add another sale of 30 at the end and print the stock again.

Predict the output

points = 10
bonus = points
points = 25
print(points)
print(bonus)

Multiple assignment

You can assign several names in one statement by separating names and values with commas. The first name gets the first value, the second name the second value, and so on:

city, temperature = "Jeddah", 34

The number of names must match the number of values, otherwise Python raises a ValueError.

You can also give several names the same value with a chain: sold = returned = 0.

Assigning several variables at once
name, role, hours = "Huda Saleh", "Cashier", 38
opened = closed = 0

print(name, "-", role, "-", hours, "hours")
print("Orders opened:", opened, "closed:", closed)

Try it: Remove the value 38 from the first line and run it. Read the error message: it tells you how many values were expected.

Swapping two values

Suppose two shift managers trade shifts. A first attempt usually looks like this:

morning = evening
evening = morning

After the first line, both names refer to the evening manager — the morning manager's name is gone, so the second line only gives evening the value it already had. One fix is a temporary variable that remembers the old value. The Python way is multiple assignment: the whole right side is worked out before any name is moved, so nothing is lost.

Two correct ways to swap
morning, evening = "Faris", "Mona"

# With a temporary variable
old_morning = morning
morning = evening
evening = old_morning
print(morning, evening)

# With multiple assignment (swaps them back)
morning, evening = evening, morning
print(morning, evening)

Try it: Add a third variable night = "Tariq" and rotate all three in one line: morning, evening, night = evening, night, morning.

Guided practice · ●difficulty 1 of 5 · about 3 min

Store a product's details

A stationery shop wants a program that stores one product's details. Create three variables:

  • item refers to the text Notebook
  • price refers to the number 12.5
  • quantity refers to the whole number 4

Then print each variable on its own line, in that order:

Notebook
12.5
4

price and quantity must be numbers, not text in quotes.

Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.

Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type

Output

Run your code to see its output, or Check to test it against the requirements.

The solution becomes available after you pass, or after all three hints and two checks.

Challenge · ●●difficulty 2 of 5 · about 6 min

Track a wallet balance

A budgeting app follows one day of spending. The starter reads the opening balance (a whole number) into balance — the tests type the value for you.

Then, in this order, reassign balance using its own previous value each time:

  1. Lunch costs 35, so subtract 35.
  2. A friend pays back 120, so add 120.
  3. Groceries cost 60, so subtract 60.

After each step print the balance with a label. For an opening balance of 200 the output is:

Start: 200
After lunch: 165
After refund: 285
After groceries: 225

At the end, balance must hold the final amount.

Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.

Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type

Output

Run your code to see its output, or Check to test it against the requirements.

The solution becomes available after you pass, or after all three hints and two checks.

Debugging · ●●difficulty 2 of 5 · about 5 min

Fix the shift swap

A clinic's rota program reads the morning nurse's name, then the evening nurse's name (the tests type them for you), and should swap the two shifts. Instead it prints the same name twice:

Morning shift: Omar
Evening shift: Omar

For the input Hana then Omar the correct output is:

Morning shift: Omar
Evening shift: Hana

Fix the program so the variables morning and evening really are swapped (the tests check the variables, not only the printed text).

Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.

Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type

Output

Run your code to see its output, or Check to test it against the requirements.

The solution becomes available after you pass, or after all three hints and two checks.

Edge cases · ●●difficulty 2 of 5 · about 5 min

Rotate three delivery routes

A courier company rotates its three drivers every week so nobody keeps the hardest route. The program reads three names (the tests type them for you, one per line) into route_a, route_b and route_c.

Rotate them so that:

  • route_a gets the driver who had route B,
  • route_b gets the driver who had route C,
  • route_c gets the driver who had route A.

Then print them. For the input Sami, Dana, Karim:

Route A: Dana
Route B: Karim
Route C: Sami

Make sure it still works when two drivers have the same name.

Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.

Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type

Output

Run your code to see its output, or Check to test it against the requirements.

The solution becomes available after you pass, or after all three hints and two checks.

Summary

  • An assignment name = value works out the right side, then makes the name refer to that value.
  • Reassigning a name replaces what it refers to; stock = stock - 12 uses the old value to compute the new one.
  • Using a name before it is assigned raises NameError.
  • Multiple assignment a, b = 1, 2 assigns several names at once; the numbers of names and values must match.
  • a, b = b, a swaps two values safely because the right side is evaluated before any name changes.