Python Quest

Track 1 · Lesson 6 of 11

Naming values with variables

A first look at variables: store a value under a name, reuse it in calculations and update it as things change.

About 25 minFirst steps4 exercisesFree

You will be able to

  • Store a value under a name with an assignment statement
  • Use variables in calculations, print() and f-strings
  • Update a variable using its current value
  • Choose clear names that follow Python's naming rules

Suppose the price of a notebook appears in five calculations in your program, and then the price changes. If you typed 12 five times, you now have to find and change every one, and missing one gives a wrong answer that's hard to spot. If you give the price a name once and use the name everywhere, you change it in one place.

A name that refers to a value is called a variable. This lesson is a first look: enough to write useful programs. The Variables and data types track goes much deeper.

Assignment

You create a variable with an assignment statement: a name, an equals sign, and a value.

price = 12

Read it as "price now refers to 12", or "store 12 under the name price". The = sign does not mean "is equal to" as it does in maths. It is an instruction: work out the value on the right, then attach the name on the left to it.

After that line, wherever you write price, Python uses 12.

Naming the values in an order
notebook_price = 12
quantity = 4
total = notebook_price * quantity

print("Notebooks:", quantity)
print("Total:", total, "SAR")
print(f"{quantity} x {notebook_price} = {total} SAR")

Try it: Change quantity to 7 on line 2 and run it. Every line that uses quantity or total updates.

Notice that there are no quotes around variable names. print(total) prints the value stored in total; print("total") prints the word total.

Python runs top to bottom, so a variable must be assigned before you use it. Using a name that hasn't been assigned yet stops the program with a NameError, the same error you get from a typo.

Updating a variable

You can assign a new value to an existing name at any time. The old value is replaced.

Very often the new value is calculated from the old one, like updating stock after a delivery:

stock = stock + 30

In maths that line would be nonsense. In Python it makes perfect sense, because the right-hand side is worked out first: take the current value of stock, add 30, then make stock refer to the result.

Tracking stock through a day
stock = 50
print("Morning:", stock)

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

stock = stock - 12   # sales
print("Evening:", stock)

Try it: Add another update for 5 returned items before the evening print.

Predict the output

a = 3
b = a
a = 10
print(a)
print(b)

Naming rules and good names

A variable name:

  • may contain letters, digits and underscores _,
  • must not start with a digit (2nd_price is not allowed, price_2 is),
  • cannot contain spaces or symbols such as - or $,
  • is case sensitive: Total and total are different variables,
  • cannot be one of Python's reserved words, such as if, for or class.

Python programmers write names in lowercase with underscores between words, such as unit_price and items_sold. This style is called snake_case. Choose names that say what the value means: unit_price tells the reader far more than x or p.

Avoid using print, input or len as variable names. Python lets you, but then the original function is hidden behind your variable.

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

Total a stationery order

The starter stores two prices. Add a variable named total that holds the cost of 2 notebooks and 5 pens, calculated from the price variables. Then print it:

Total: 39 SAR

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 5 min

Track warehouse stock

Write a program that tracks stock of printer paper with one variable named stock:

  1. Start with stock = 120 and print the opening stock.
  2. A delivery of 45 reams arrives: update stock and print it.
  3. 30 reams are sold: update stock again and print it.
Opening stock: 120
After delivery: 165
After sales: 135

Update the variable with lines like stock = stock + 45; don't type the results 165 and 135.

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 budget program

This monthly budget program stops with a NameError instead of printing:

Monthly budget: 4500
Left after rent: 1700

Find and fix the problems. Don't change the numbers.

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

Swap two shifts

Omar and Lina have agreed to swap shifts. The program stores who works each shift. Add code where shown so that the values of morning and evening are swapped, then the program prints:

Morning: Lina
Evening: Omar

Swap the values using the variables themselves, not by typing the names "Lina" or "Omar" again. Watch out: once you assign a new value to morning, its old value is gone, unless you saved it under another name first.

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, stores a value under a name. The right-hand side is worked out first.
  • Use the name (without quotes) anywhere you would use the value: in calculations, print() and f-strings.
  • Assigning again replaces the value; stock = stock + 30 updates a variable from its current value.
  • Names use letters, digits and underscores, can't start with a digit, and are case sensitive. Prefer clear snake_case names.