Variables — labelled bags

In a school bag, the pencil box is labelled so it is not mixed with tiffin. A variable is a labelled bag in the computer’s memory: the name stays on the outside, the contents can change. When Asha says pencils = 8 she is not writing poetry — she is putting the number 8 into a bag named pencils.

Labelled school bag

Variables are named pockets.

You will be able to

  • Create variables with =
  • Store numbers and text in named bags
  • Print a variable and use it in a later line

Assignment is putting something in a bag

The symbol = in Python is not the “equals” of a maths identity. It is an action: evaluate the right-hand side, store that result in the name on the left. pencils = 8 means “bag pencils now holds 8”.

Later, pencils = 7 replaces the contents. The old 8 is gone. There is no history unless you saved it in another variable. That is why we name carefully — you will look for this bag again.

Names you (and Python) can read

Use lowercase words that say what is inside: total, marks, city, bus_fare. Do not start with a number. Do not use spaces. An underscore joins words: house_points.

Python is case-sensitive: Marks and marks are different bags. Stick to lowercase so you never wonder which one you meant. Avoid names like list or print — those already mean something to Python.

Two kinds of contents you will use today

Integers are whole numbers: 8 pencils, 40 rupees, class 7. Strings are text: "Asha", "Blue". Mixing them in print is fine: print("Pencils", pencils). Mixing them with + is not: "Asha" + 8 is a type error in real Python.

When you are unsure what a bag holds, print it. The console is your X-ray. Professional programmers still do this — they just call it logging.

Words that matter

Variable
A named place in memory that holds a value.
Assignment
The = action that stores a value in a name.
Integer
A whole number, like 12 or 0.

Common mistakes

Avoid: Thinking = asks a question (is it equal?).

Do this: Use = to store. Use == later, in if, to compare.

Avoid: Naming a variable x1, tmp2, data3 with no meaning.

Do this: Name after the real thing: erasers, bus_fare, house.

Example program — Asha's school bag

Change the numbers and Run again. The printed totals follow the bags, not the old story in your head.

Python sandboxlesson://workspace
console

Edit the example, press Run, then Build if you want a compile check.

build

Press Build to compile.

Your turn — Count your kit

Store notebooks as 4 and pens as 3. Print a line that includes the total 7.

Python sandboxlesson://workspace
console

Edit the example, press Run, then Build if you want a compile check.

build

Press Build to compile.

Self-assessment

Check your understanding before you mark the lesson complete.

1. After x = 5 then x = 9, print(x) shows…
2. A legal variable name is…
3. pencils = 8 does what?

Progress is stored in a browser cookie on this device.