◀ Course contents Part 1 · Module 1-02

Variables & Names

Give a value a name and it stops being a mystery

A program that only prints fixed text is a very expensive way to write a note. The moment you store a value under a name, you can reuse it, change it, and calculate with it. This module covers what assignment actually does, why one mental model of it makes everything easier, and how to choose names that save the next reader from guessing.

Ready?

1

Assignment: Putting a Value Under a Name

A variable is a name that points at a value. You make one by writing the name, a single =, and the value:

player_name = "Rookie"
level = 1
xp = 0

Nothing is printed. Assignment is silent — it stores something and moves on. From that point the name works anywhere the value would: print(level) shows 1.

Read = as "gets", never as "equals"

x = 5 is not a claim that x and 5 are the same. It is an instruction: x gets 5. Python works out the right-hand side first, then attaches the name on the left to the result. Hold on to that reading — it is what makes the line score = score + 10 sensible instead of mathematically impossible.

Fragile

Repeating the value

print(4.25) in six places. Change the price and you have six edits and one you will miss.

Sturdy

Naming it once

unit_price = 4.25, then use the name everywhere. One edit changes all six.

Quick check

What does the line total = 3 * 4 leave stored under total?

2

A Variable Is a Label, Not a Box

Most beginner material describes a variable as a box you put a value into. It is an easy picture and it will mislead you within a week. Python actually works the other way round: the value exists, and the name is a label stuck to it.

One value, many labels

a = b does not copy anything. Both names now point at the same value.

Reassigning moves a label

It never disturbs the value, and never disturbs any other name pointing at it.

Unlabelled values disappear

When the last name pointing at a value moves away, Python quietly reclaims it.

The payoff shows up immediately in a swap. Because Python builds the whole right-hand side before handing anything out, two names can trade values in one line, with no temporary variable:

one, two = two, one

The bigger payoff comes in Part 2, when lists arrive. Two names pointing at the same list means changing it through one name changes what the other one sees — behaviour that is baffling under the box model and obvious under this one.

Quick check

After a = 5 then b = a then a = 9, what is b?

3

Values That Change Over Time

Assign to a name that already exists and it simply points somewhere new. That is how counters count and totals total:

score = 0
score = score + 10   # right-hand side first: 0 + 10, so score gets 10
score = score + 15   # 10 + 15, so score gets 25

That middle line is the one people stare at. It is not saying "score equals score plus ten" as a fact. It is saying: take the current score, add ten, and put the answer back under the same name.

Because this shape is so common, Python has a shorthand for it, called augmented assignment:

score += 10   # exactly the same as score = score + 10
lives -= 1
price *= 2

The name has to exist first

score += 10 reads the current value before writing the new one, so a score that has never been assigned gives you a NameError. Start your counters at zero explicitly. That one line also tells the reader what the starting point is meant to be.

Quick check

lives = 3, then lives -= 1 twice. What is lives?

4

Naming: The Rules, and the Conventions

The rules are what Python enforces. Letters, digits and underscores only; never starting with a digit; no spaces; and not one of Python's own reserved words like if, for or class. Case matters: score and Score are two different variables.

The conventions are what other Python programmers expect. Lowercase words joined by underscores — items_in_cart — which the community calls snake_case. Nothing breaks if you ignore it, but your code stops looking like Python.

Costs the reader

x = 250

Two hundred and fifty what? The reader has to scan the rest of the file to find out.

Pays the reader

item_price = 250

The line explains itself, and any line using it explains itself too.

The test that actually matters

A good name is one that lets someone read a line in the middle of your program and follow it without scrolling up. if days_until_renewal < 7: passes that test. if d < 7: does not, and the person who pays for it is usually you, some weeks later, with no memory of what d stood for.

Names are documentation you cannot forget to update.

Quick check

Which of these is a valid Python variable name that also follows the usual convention?

0 of 9 completed

Real Python runs right here in your browser — nothing to install, nothing sent to a server. The interpreter downloads once the first time you press Run, then stays cached.

01

To do

A variable is a name pointing at a value. You create one by writing the name, an =, and the value:

player_name = "Rookie"

Read = as "gets", not as "equals". It is an instruction — put this value under this name — not a statement of fact.

Your task: create player_name holding the text Rookie, and level holding the number 1. Then print them on one line so the output reads exactly Rookie is on level 1.

your_code.py
Python
Hint

The text needs quotes, the number does not. For the output, print("...", "is on level", ...) — commas add the spaces for you.

Output

      
    02

    To do

    A variable is not fixed. Assign to it again and the name simply points at the new value; the old one is gone.

    lives = 3
    lives = 2 # the name now points at 2

    This line trips up almost everyone at first: score = score + 10. It looks like a contradiction, but remember = means "gets". Python works out the right-hand side first (the old score plus ten), then puts that answer under the name score.

    Your task: start score at 0, print it, then add 10 and print it, then add 15 and print it. Three lines of output: 0, 10, 25.

    your_code.py
    Python
    Hint

    score = score + 10 puts the new total back under the same name. Python has a shorthand for it too: score += 10.

    Output
    
          
      03

      To do

      score = score + 10 is so common that Python gives it a shorthand. score += 10 means exactly the same thing, and the same trick works for the other operators:

      score += 250   # add
      score -= 100 # subtract
      score *= 2 # multiply

      Your task: a player finishes a round. Start score at 0 and apply four changes in order, using the shorthand each time, printing the running total after every one:

      1

      Puzzle solved

      add 1250

      2

      First-try bonus

      add 480

      3

      Hint used

      subtract 100

      4

      Double-score weekend

      multiply by 2

      Four lines of output: 1250, 1730, 1630, 3260.

      your_code.py
      Python
      Hint

      score += 1250 then print(score), and so on. The last one is score *= 2 — the doubling applies to the total, not to the last bonus.

      Output
      
            
        04

        To do

        This is the bug that catches everyone once. total = price * 3 does not tie total to price. It works the answer out once, using the price as it stands at that moment, and puts that answer under the name. Change the price afterwards and the total has no idea.

        Your task: the code below prices three seats, then the price goes up. Print the stale total, then work the total out again and print the correct one.

        750
        900

        Do not change the first three lines.

        your_code.py
        Python
        Hint

        The first print needs nothing but total. Then repeat the line that made it — total = price * 3 — now that price says 300.

        Output
        
              
          05

          To do

          Two players sit at positions one and two. They change seats. In most languages that needs a third, temporary variable — Python can do it in a single line:

          a, b = b, a

          Python builds the right-hand side first, out of the current values, and only then hands them back out to the names on the left. That is why nothing gets overwritten halfway.

          Your task: swap the values in one and two without changing the two lines that create them, then print them in that order.

          your_code.py
          Python
          Hint

          One line: one, two = two, one — then the existing print does the rest.

          Output
          
                
            06

            To do

            Python does not care what you call things. Everyone who reads your code afterwards does — and that includes you.

            The rules: letters, digits and underscores only; no starting with a digit; no spaces. The convention: lowercase words joined by underscores, which Python programmers call snake_case.

            Your task: this code works but reads like a puzzle. Rewrite it using the names item_price, item_count and total_cost, keeping the same numbers and the same result. Print the total on its own line.

            your_code.py
            Python
            Hint

            Same maths, better names: item_price = 250, item_count = 3, total_cost = item_price * item_count.

            Output
            
                  
              07

              To do

              A name can hold letters, digits and underscores. It cannot start with a digit, cannot contain a space, and cannot be one of the roughly thirty-five words Python has reserved for itself — class, if, for, None and the rest.

              Case matters too. total and Total are two different names, and Python will not connect them for you.

              Your task: three faults, three different complaints from Python. Run it, fix the first thing it names, run again. Use first_place and belt for the two renamed variables, and leave total as it is. The output should be:

              Ada Gold 250
              your_code.py
              Python
              Hint

              A name cannot begin with a digit, so 1st_place becomes first_place. class is reserved, so pick belt. And Total was never created — total was.

              Output
              
                    
                08

                To do

                A bare number in the middle of a calculation is called a magic number: it works, and nobody reading it knows what it means or dares change it. Give it a name and it explains itself.

                When a value is fixed for the whole program, Python programmers name it in UPPER_CASE. Python does not enforce this — nothing stops you reassigning it — but every reader takes it as "this one is not meant to move".

                VAT_RATE = 0.2
                total = subtotal + subtotal * VAT_RATE

                Your task: rewrite the code below so the two magic numbers become the constants VAT_RATE and SHIPPING, then print the total:

                Total: 5390.0
                your_code.py
                Python
                Hint

                Two new lines above: VAT_RATE = 0.2 and SHIPPING = 350. Then the calculation reads total = subtotal + subtotal * VAT_RATE + SHIPPING, and each number appears exactly once in the whole file.

                Output
                
                      
                  09

                  To do

                  A support ticket arrives: "the job gives up after 30 milliseconds". The value was never wrong. The name simply never said which unit it was in, so the next person to touch it guessed — and guessed wrong.

                  Any number with a unit should carry it in the name. timeout_seconds, file_size_mb, delay_ms. It costs a few characters and removes an entire category of bug.

                  Your task: rename timeout to timeout_seconds, add timeout_ms worked out from it, and print:

                  Giving up after 30000 ms
                  your_code.py
                  Python
                  Hint

                  timeout_seconds = 30, then timeout_ms = timeout_seconds * 1000. Do the multiplication in code rather than typing 30000, so the two can never disagree.

                  Output
                  
                        

                    The end-of-week report

                    To do

                    Every Sunday the dojo mails each learner a one-screen summary of their week. Write the code that works one out and prints it.

                    Set up these, with exactly these names:

                    • EXERCISES_PER_MODULE9, a constant
                    • LESSONS_PER_MODULE4, a constant
                    • learner_name — the text Kenji
                    • modules_completed — the number 7
                    • parts_completed — the number 1
                    • tasks_donecalculated from the constants and modules_completed

                    Then a late assignment is marked and one more module completes. Add it to modules_completed using the shorthand, work tasks_done out again, and print the corrected report:

                    Learner: Kenji
                    Modules: 8
                    Parts: 1 complete
                    Tasks: 104

                    Nothing in the report may be typed in as a finished number. Both 8 and 104 have to come out of the arithmetic — that is the whole point of the exercise.

                    your_code.py
                    Python
                    Hint

                    tasks_done = modules_completed * (EXERCISES_PER_MODULE + LESSONS_PER_MODULE). After modules_completed += 1, that same line has to run again — a total is a snapshot, not a link.

                    Output
                    
                          

                      Notification