livepython.net
CHAPTER 04Variables
4.3  HOW THEY WORK

How Python Variables Work: Reassign, Swap and More

Changing a Variable's Value

A variable can change. Assign a new value, and it replaces the old one:

PYTHONedit me
language = "Java"
language = "Python"
print(language)
OUTPUT
Python

This is called reassignment. The old value, "Java", is gone. A variable holds only one value at a time, and it keeps no history.

Think of a whiteboard: when you write a new value, you wipe the old one first.

Change it using its own value

You can even calculate a new value from the old one:

PYTHONedit me
score = 10
score = score + 5
print(score)
OUTPUT
15

This line looks strange in maths, but in Python it makes sense. Read it as "score gets score plus 5":

  1. Python works out the right side first: 10 + 5 is 15.
  2. Then it stores 15 back in score.

This is how games add points, shops update stock, and counters count. You'll see a shorter way to write it in the Data Types chapter.

Order still matters

Python runs top to bottom, so a print() shows the value at that moment:

PYTHONedit me
lives = 3
print(lives)
lives = 2
print(lives)
OUTPUT
3
2

Assign a new value, and the old one is replaced. A variable remembers only its latest value.

your turnPredict the output

What will this print?

x = 5 x = 8 print(x)
Your turn! What will this code show on the screen?
your turnType the output

Type what this prints

score = 10 score = score + 5 print(score)
Read the code line by line, then type the output exactly.

Assigning Several Variables at Once

Python has two handy shortcuts for giving values to several variables in one line.

The same value to many variables

Chain the names with =:

PYTHONedit me
x = y = z = 0
print(x, y, z)
OUTPUT
0 0 0

This is called chained assignment. All three variables get 0. They're still three separate boxes: change one later, and the others keep their value.

PYTHONedit me
red = green = blue = 0
red = 255
print(red, green, blue)
OUTPUT
255 0 0

Different values in one line

Put the names on the left and the values on the right, both separated by commas:

PYTHONedit me
name, age, city = "Sunny", 25, "Pune"
print(name, age, city)
OUTPUT
Sunny 25 Pune

The first name gets the first value, the second gets the second, and so on. The counts on both sides must match, or Python stops with an error:

PYTHONedit me
a, b = 1, 2, 3
OUTPUT
ValueError: too many values to unpack (expected 2, got 3)

When to use them

  • Chained assignment is great for starting values: counters, scores, totals.
  • Several values in one line is great for things that belong together, like a name and an age. But don't overdo it: five variables in one line are hard to read.

Many names, one value: x = y = 0. Many names, many values: a, b = 1, 2.

your turnPredict the output

What will this print?

a, b = 1, 2 print(b, a)
Your turn! What will this code show on the screen?

Swapping Two Variables

Sometimes you need to swap two values: a should get b's value, and b should get a's. It's harder than it looks:

PYTHONedit me
a = "tea"
b = "coffee"
a = b
b = a
print(a, b)
OUTPUT
coffee coffee

What went wrong? a = b replaced "tea" with "coffee", so the tea was lost before b could get it.

The classic way: a temporary variable

Think of swapping the drinks in two full cups. You need a third, empty cup:

PYTHONedit me
a = "tea"
b = "coffee"
temp = a
a = b
b = temp
print(a, b)
OUTPUT
coffee tea
  1. Pour a into temp.
  2. Pour b into a.
  3. Pour temp into b.

The Python way: one line

Python can swap in a single line, using the "several values at once" trick from the last lesson:

PYTHONedit me
a = "tea"
b = "coffee"
a, b = b, a
print(a, b)
OUTPUT
coffee tea

Python first reads both values on the right ("coffee" and "tea"), then puts them into a and b. Nothing is lost, and you don't need a temporary variable.

Most other languages need the temporary variable, so it's good to understand both ways.

Swap in one line with a, b = b, a.

your turnFill the gap

Make it swap the drinks

a = "tea" b = "coffee" a, b = ? print(a, b)

It should print: coffee tea

Which piece makes this code work?

Create a Variable Before You Use It

Python runs your code from top to bottom, as you learned in chapter 1. So a variable must be created before a line uses it:

PYTHONedit me
print(total)
total = 50
OUTPUT
NameError: name 'total' is not defined

On line 1, total doesn't exist yet. Line 2 would create it, but Python never gets there. Swap the two lines, and it works.

Copying a value

You can create a variable from another one:

PYTHONedit me
a = 10
b = a
a = 20
print(a, b)
OUTPUT
20 10

b = a copies the value 10 into b at that moment. Changing a later doesn't change b. The two variables aren't linked: each keeps its own value.

Think of it like copying a friend's phone number into your phone. If they get a new number, your copy doesn't update by itself.

Plan your order

Before you write a calculation, make sure every value it needs is already stored:

  1. Create the values: price = 20, quantity = 3.
  2. Calculate with them: total = price * quantity.
  3. Show the result: print(total).

This is the same "store, calculate, show" order you'll use in almost every program.

Create first, use after. Python reads top to bottom.

your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.
your turnOrder the lines

Put the lines in order to print 5

  1. oranges = 2
  2. apples = 3
  3. fruit = apples + oranges
  4. print(fruit)
These lines are mixed up. Put them back in order, then press Check.

Practice: How they work

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 19.Python Program to Assign One Value to Several VariablesEasySolve
  2. 20.Python Program to Reassign a VariableMediumSolve
  3. 24.Python Program to Swap Two Variables Without a Temporary VariableMediumSolve
  4. 25.Python Program to Rotate the Values of Three VariablesMediumSolve