Skip to contentSkip to navigation

Module 01 · Lesson 03

Variables & Dynamic Typing

Store values under names, change them as the program runs, update them with +=, swap two at once, and mark values that should never change as constants.

  • About 8 minutes
  • Beginner friendly
  • 12-question quiz at the end

What you will learn

  • Name a value
  • Change and swap
  • Watch names update
  • Constants in capitals

Give a value a name

A variable is a name you stick on a value, so your program can find it again later.

  • Name it

    score = 0 sticks the name score on the value 0. The = means "store", not "is equal to".

  • Change it

    Write score = 10 later and the name moves to the new value. The old one is simply forgotten.

  • Name rules

    Letters, digits and underscores only, never a digit first. Score and score are two different names.

  • CONSTANTS

    A name in capitals, like MAX_LIVES = 3, tells people "please do not change this".

Every app remembers with names

Behind each number or word that changes on a screen sits a variable.

  • Game scoresA game keeps score, lives and level and changes them every time something happens.
  • Music playersThe song playing now and the volume are two variables that update as you tap.
  • Weather appsToday's temperature is stored under a name and shown in big numbers on the home screen.
  • Step countersA watch adds 1 to a steps variable every time you take a step.

Right side first, then store

Python reads an assignment from the right. Tap each part to see its job.

Part 1 of 5

Tap any part of the code below, or press Next.1 of 5 explored

new name:The name that gets the answer. It is filled in last, after the right side is worked out.

Make names and change them

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Name things

Each line stores a value under a name. print() then shows what the names point to.

Your turn: Add a town variable and print one more line about Sam's town.

Python
name = "Sam"
age = 12
pet = "dog"
print(name, "is", age)
print(name, "has a", pet)
Output
Press Run to see what it prints.

Watch the names change

Press Step to run one line at a time. Keep an eye on the names box: which values change, and which stay put?

Ready. Press Step to run the first line.

  1. coins = 10
  2. coins = coins + 5
  3. bonus = coins * 2
  4. coins = 0
  5. print("coins:", coins)
  6. print("bonus:", bonus)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

No type label needed

Storing one score in Python and in two other languages.

Language 1 of 2Python vs Java

Python2 lines
score = 0
score = "zero"

No keyword and no type. The same name can later hold text instead of a number: Python checks the value, not the name.

Javatype first
int score = 0;
score = "zero";  // error: score holds int only

Java fixes the type when the name is made. Putting text in an int name stops the program before it runs.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.What does this print?

a = 5
b = a
a = 9
print(b)

0 of 6 answered

Common name misconceptions

Each card is something beginners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Names that refer to values

A variable is a name that refers to a value. You create one with the assignment operator, a single equals sign.

Try it 1: edit me, then Run
city = "Lisbon"
temperature = 21
print(city, temperature)
Output
Press Run to see what it prints.

Read temperature = 21 as "let temperature refer to 21", not as a maths equation. Python always works out the right side first, then attaches the name on the left to the result. That is why this line makes sense:

Try it 2: edit me, then Run
count = 10
count = count + 1
print(count)
Output
Press Run to see what it prints.

On the second line Python reads the current value of count (10), adds 1, and then makes count refer to the new value, 11. The old value is simply forgotten. A variable can be given a new value as often as you like, and the newest assignment always wins.

A name must be assigned before it is used. If a line uses a name that has not been created yet, Python stops with NameError. Because Python runs from top to bottom, the assignment must come on an earlier line.

Labels, not boxes

People often picture a variable as a box with a value inside. A closer picture for Python is a label tied to a value. The value lives somewhere in the computer's memory, and the name is a label pointing at it. Two names can point at the same value:

Try it 3: edit me, then Run
price = 12
old_price = price
price = 15
print(old_price, price)
Output
Press Run to see what it prints.

This prints 12 15. The line old_price = price ties a second label to the value 12. When price is later moved to 15, old_price still points at 12. Assignment never changes a value; it only moves a label. This picture will matter again when you meet lists, which can be changed in place, but for numbers and text the rule is simple: reassigning one name never affects another.

Rules for names

Python accepts a name if it:

  • uses only letters, digits and underscores (_),
  • does not start with a digit,
  • is not one of Python's reserved keywords, such as if, for, class, True or None.

So score, player_2 and _hidden are valid, while 2nd_place, my-score and class are not. Names are case sensitive: Score and score are two different variables, which is a common source of confusion when one is spelled differently in one place.

Beyond the rules there is a convention, a habit everybody follows to keep code readable. Ordinary variables use lowercase words joined by underscores, called snake_case: total_price, days_left. Choose names that say what the value means. minutes_per_day makes a line explain itself; m forces the reader to guess.

Avoid reusing the names of built-in tools such as print, input, list or sum. Python allows print = 5, but afterwards print("hi") fails, because the name now refers to a number.

Constants

Some values should never change while a program runs: the number of days in a week, a tax rate, the maximum number of lives in a game. Python has no special keyword to lock them. Instead, the convention is to write the name in UPPER_CASE, as a promise to every reader that the program will not reassign it.

Try it 4: edit me, then Run
DAYS_PER_WEEK = 7
TAX_RATE = 0.2
price = 50
print(price + price * TAX_RATE)
Output
Press Run to see what it prints.

If the tax rate changes next year, you edit one line at the top instead of hunting for 0.2 all through the program. That is the real benefit of constants: one value, one place.

Updating with augmented assignment

Changing a variable based on its own value is so common that Python has a shorter form. score += 5 means score = score + 5. The same pattern works with other operators.

Try it 5: edit me, then Run
lives = 3
lives -= 1      # same as lives = lives - 1
points = 10
points *= 2     # same as points = points * 2
print(lives, points)
Output
Press Run to see what it prints.

This prints 2 20. The variable must already exist; += on a name that was never assigned is a NameError.

Several names at once

You can assign several variables in one line by separating names and values with commas. The values are matched up in order.

Try it 6: edit me, then Run
width, height = 4, 3
print(width * height)
Output
Press Run to see what it prints.

This also gives Python a neat way to swap two values. Because the whole right side is worked out before any name changes, a, b = b, a swaps them without a temporary variable.

Try it 7: edit me, then Run
first, second = "sun", "moon"
first, second = second, first
print(first, second)
Output
Press Run to see what it prints.

The output is moon sun. In many other languages a swap takes three lines and an extra name; in Python it is one clear line.

Finally, a variable does not have a fixed type. x = 5 and then x = "five" is allowed: the name simply moves to a new value. That freedom is handy, but a name that changes what kind of thing it holds is confusing to read, so keep each variable to one kind of value. The next lesson looks at those kinds, called types.

Syntax

The general shape of the statements in this lesson.

syntax.py
name = value              # create or replace a variable
count = count + 1         # right side first, then store
count += 1                # the same, shorter (-=, *=, /= too)
x, y = 1, 2               # several names at once
x, y = y, x               # swap
MAX_SPEED = 120           # constant: UPPER_CASE by convention
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

A savings tracker

Beginner

Start with 20 in savings, add 15 for each of three weeks with +=, spend 12, and print the balance after each step.

Python
WEEKLY_SAVING = 15
savings = 20
savings += WEEKLY_SAVING
savings += WEEKLY_SAVING
savings += WEEKLY_SAVING
print("After three weeks:", savings)
savings -= 12
print("After the cinema:", savings)
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

WEEKLY_SAVING is a constant, so changing the weekly amount means editing one line. Each += reads the current balance, adds the saving and stores the result. The variable keeps changing, and each print shows its value at that moment in the program.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Starting a name with a digit

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
2nd_place = "Lee"
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

SyntaxError: invalid decimal literal

Write this instead

second_place = "Lee"

Why it happens

Python reads a leading digit as the start of a number, so it cannot be a name.

In the real world

Where this shows up in software people use every day.

  1. Counting visitors at a door

    Events

    A volunteer at a school fair counts visitors in and out with a simple program, so they always know how many people are inside.

    Why Python fits

    The capacity never changes, so it is a constant. The count changes with every arrival and departure, so it is an ordinary variable updated with += and -=.

    Python
    CAPACITY = 120
    inside = 0
    inside += 45
    inside += 30
    inside -= 12
    print("Inside now:", inside)
    print("Space left:", CAPACITY - inside)
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Is a constant really locked?

No. Python will let you reassign it. UPPER_CASE is a promise to readers, and tools that check code style will warn you if you break it.

Can a variable change from a number to text?

Yes, Python allows it, but it makes code hard to follow. Keep each name to one kind of value.

What is the difference between = and ==?

= stores a value under a name. == asks whether two values are equal and gives True or False. You will use == in the lesson on conditions.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/4 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 6 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.