Menu

Variables

Assigning Calculations and Strings

An 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.

Joining strings with +

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 court

Practise this