Learning LibraryCore Coding LibraryKids

Variables: give a value a name

A variable is how a program remembers things. Give a value a name once. Then use it, or change it, on any line below.

The big idea

A variable holds a value under a name. Your program can use that value later, or swap it for a new one.

See it in code

1Start simple

The name goes on the left, then =, then the value to keep. After that, the name stands in for the value:

python
cookies = 12
print("Cookies left:", cookies)
Press the 'Run Code' button and the name hands back its value:
Cookies left: 12

cookies has no quotes around it, so Python doesn't print the word. It looks inside the variable and prints what it finds there.

2A step further

A variable can change. The third line reads the old number, takes one away, and stores the answer back under the same name:

python
cookies = 12
print("Cookies left:", cookies)
cookies = cookies - 1
print("Cookies left:", cookies)
The same print line, run twice, shows two different numbers:
Cookies left: 12
Cookies left: 11

A cookie sold, so the count dropped. Both print lines are the same. They show two numbers because the variable changed in between.

3In the paint studio

In the paint studio a variable is called a jar. Here one jar, sun_y, holds how far down the sun sits, and two shapes read it:

python
sun_y = 150
paper("light salmon")
circle(x=200, y=sun_y, size=130, color="light yellow")
circle(x=200, y=sun_y, size=90, color="gold")
rect(x=200, y=300, width=400, height=200, color="turquoise")
Two circles, one jar:
A gold sun with a pale yellow glow setting behind a turquoise sea, on salmon-colored paper.

The glow and the sun share one jar, so they sit together. Change the jar and both shapes move at once. They both read the same number.

The same idea, everywhere

Every program leans on variables. A bakery keeps its prices in them. A painting keeps its sizes in them. A game keeps its score in one.

Try it yourself

Change sun_y = 150 to sun_y = 60 and run it: the sun rises. Then make a second jar, sun_x, and use it for both circles' x. Now two numbers move your whole sun.

The common mistake

Using a variable before it exists. Lines run from top to bottom, so print(cookies) placed above cookies = 12 stops with a NameError. Make the variable first, then use it.

What it unlocks

Once values have names, you can do math with them, drop them into sentences with f-strings, and keep a running total inside a loop.

Older, or want more depth? Read the Teens version →