Programming Fundamentals
A variable is a named location in the computer's memory where a value is kept. While the program runs, that value can change, so one name can hold one value near the start of a program and a different value later on.
At any moment a variable holds a single value. Assigning a new value replaces whatever was stored before, and the old value is lost — the computer keeps no copy of it. If a variable is assigned the value 92 and later assigned 17, it now holds 17 and the 92 has gone.
The latest assignment is the one that counts: whenever the program uses the variable, it uses the value stored most recently. So one variable can be given a new value as many times as you like as the program runs.
# each assignment replaces the previous value
game_level = 'Forest'
game_level = 'Cave'
game_level = 'Castle'
print('Current level:', game_level)Output:
Current level: Castle
In a program, variables are the names that are given values and whose values can change. The quickest way to find them is to look for a name followed by a single equals sign, which assigns the value on the right to that name.
Not every value in a program is a variable. A fixed value written straight into the code, such as a number or some text in quotation marks, is just data: it has no name and it cannot change. In game_level = 'Castle', game_level is a variable because it is a name holding a value, while 'Castle' is a fixed value. Function names such as print are not variables either.
A variable name can appear anywhere its value is needed, including inside print(); it is still the same variable, holding whatever value it has at that point in the program.
A variable name is the label you choose for a variable in your program. Python only accepts names that follow a few rules, and there are some good habits that make your programs easier for other people to read.
lap-time means lap take away time.3laps is rejected, but laps3 is accepted.if, class and None already have a job in Python, so using one as a name would confuse the interpreter.wins and Wins are two completely separate variables, so a stray capital letter creates a new variable instead of updating the one you meant.| Name | Valid? | Reason |
|---|---|---|
lap_time | yes | letters and an underscore only |
lapTime | yes | letters only, with no spaces or symbols |
3laps | no | starts with a digit |
lap time | no | contains a space |
lap-time | no | the hyphen is read as a minus sign |
class | no | it is a keyword |
Pick a meaningful name that describes the value stored. homeTeamGoals tells a reader far more than h, so another programmer can tell what it holds without tracing through the whole program. Meaningful names also make your own code easier to check when you come back to it.
When a name needs more than one word, join the words in one of two styles: camelCase, where the first word is lower case and each new word starts with a capital letter with no spaces (shotSpeed), or underscores (shot_speed). Both are accepted by Python, but choose one style and keep to it, so the code reads consistently from top to bottom.
# one style throughout: underscores between words
book_title = "The Lost Robot"
total_pages = 128
pages_read = 42
pages_left = total_pages - pages_read
print(pages_left)Output:
86An assignment stores a value in a variable using a single equals sign. The computer works out everything on the right of the equals sign first, then places the result in the variable named on the left. That value can be a fixed value or the result of a calculation.
At a craft stall, packs = 4 stores a fixed value. Then beads = packs * 25 works out 4 * 25 first and stores 100 in beads. Swap the two sides and it stops making sense: packs * 25 = beads is not an assignment, because the left of the equals sign must be one variable name, never a calculation or a fixed value.
The calculation uses the values the variables hold at the moment the line runs. If packs is given a new value later, beads keeps 100 until another assignment stores a fresh result in it.
When the values either side of + are strings, the + joins them into one new string rather than adding them numerically. The result can be stored in a variable, just like a number.
Suppose animal = 'otter' and habitat = 'river'. Then label = habitat + ' ' + animal stores river otter in label. The middle ' ' is a string holding a single space, so the words are separated; leave it out and you get riverotter with the two words glued together.
Joining does not change the variables used. habitat still holds river and animal still holds otter; the new variable holds the combined text, ready to be used or printed.
packs = 3
stickers = packs * 12
total = stickers + 5
print(total)
sport = 'tennis'
place = 'court'
sentence = sport + ' is played on a ' + place
print(sentence)Output:
41
tennis is played on a courtInside print(), a variable name without quotation marks makes Python find the value stored in that variable and display it. Text wrapped in quotation marks is a string literal: Python displays exactly those characters and does not look for a variable with that name.
playlistName = 'Revision Mix'
print(playlistName)
print('playlistName')
print('72 minutes long')Output:
Revision Mix
playlistName
72 minutes long
The first two print lines use the same word, playlistName, but only the first has no quotation marks. The first print() displays the value stored in the variable. The second displays the characters playlistName, because the quotation marks turn it into text. The variable still holds its value afterwards; printing does not change it.
To work out what a line prints, check what sits inside the brackets. If it is a variable name, find its current value first, then print that value. If it is inside quotation marks, copy the characters between the marks exactly, including capital letters and spaces.
| Inside print() | What is displayed |
|---|---|
playlistName (a variable) | The value the variable currently holds |
'playlistName' (text in quotation marks) | The characters playlistName |
An update changes a variable using the value it already holds. For example, passengers = passengers + 3 works out the current value of passengers, adds three, and stores the result back in passengers. Programs use this to keep a running total, count events, or take an amount away.
The right-hand side of = is worked out first, using the value the variable holds at that moment. The result then replaces the old value. So the variable name must be written on both sides: the right side uses the current value, and the left side names where the new value is stored. The old value is used before it is replaced.
A variable must already hold a value before you use it in an update. budget = budget - 4 cannot work if budget has never been set, because there is no current value to subtract 4 from, so the program stops with an error. Set budget = 20 first, and the update will run.
# The variable is used before it has been given a value
budget = budget - 4
print(budget)Output:
NameError: name 'budget' is not defined (line 2)A running total adds values up as a program runs. Start the total at zero, then keep adding to that same variable each time a new value arrives. The right-hand side uses the total as it stands, and the result becomes the new total.
# Cake sale takings for the school trip
funds = 0
funds = funds + 18
funds = funds + 23
print("Trip fund so far:", funds)Output:
Trip fund so far: 41If funds holds 18 and the next line is funds = funds + 23, the right side works out 18 + 23 = 41 and stores 41 back in funds. The 18 is replaced, but it was used in the sum. Without starting at zero, the first update has no total to add to and the program fails.
When a program is a sequence of assignments, you can follow the value of every variable by working down it one line at a time. After each assignment, write down the value that each variable now holds. Any variables on the right of an assignment use the values they hold at that moment, then the result replaces the value of the variable on the left.
Work out the right-hand side first, then store the result in the variable named on the left. Storing a value removes whatever that variable held before, so the next line sees the new value rather than the old one.
crates = 18
bottles = crates * 6
crates = 12
bottles = crates * 6
print(bottles)Output:
72| After this line | crates | bottles |
|---|---|---|
| 1 | 18 | - |
| 2 | 18 | 108 |
| 3 | 12 | 108 |
| 4 | 12 | 72 |
Line 2 uses the value held by crates at that point, 18, so bottles becomes 108. Line 3 replaces the 18 in crates with 12, so the 18 has gone. Line 4 works out crates * 6, which is 12 * 6, so bottles becomes 72 in place of 108. A dash in the table means the variable has not been given a value yet.
When a line prints a variable, the value shown is the one the variable holds when that line runs. A later assignment does not change what has already been printed.
slices = 24
people = slices // 3
print(people)
slices = 18
people = slices // 3
print(people)Output:
8
6people has been given the value 8 before line 3 prints it, so 8 appears. Line 4 replaces slices with 18, and line 5 recalculates people as 6, so the final print shows 6. The 8 printed earlier stays as 8.
To swap two variables means to exchange the values they hold, so the value stored in the first ends up in the second and the value in the second ends up in the first. Copying one variable straight into the other does not do this: one of the two values is lost at once.
Imagine a games club where two players' points totals were typed into the wrong variables and now need exchanging. Suppose scoreA = 458 and scoreB = 291. If you wrote scoreA = scoreB first, scoreA would hold 291 and the 458 would be lost for good. The next line, scoreB = scoreA, would then copy 291 into scoreB as well, so both variables would end up on 291 and one player's score would have vanished.
A temporary variable is a third variable that holds one value for a moment so that it is not overwritten. Copy scoreB into spare, copy scoreA into scoreB (safe now, because the 291 is saved), then copy spare into scoreA. The order matters: the copy into spare must happen before the variable it saves is overwritten.
| Step | Assignment | scoreA | scoreB | spare |
|---|---|---|---|---|
| Start | none | 458 | 291 | not assigned |
| 1 | spare = scoreB | 458 | 291 | 291 |
| 2 | scoreB = scoreA | 458 | 458 | 291 |
| 3 | scoreA = spare | 291 | 458 | 291 |
The temporary variable holds a value, not an index or a position: spare holding 291 is a copy of that score, not a note of where the score is stored. It simply keeps one value safe while the other variable is overwritten.
scoreA = 458
scoreB = 291
spare = scoreB # keep scoreB's value before it is overwritten
scoreB = scoreA
scoreA = spare
print(scoreA)
print(scoreB)Output:
291
458