Menu

Writing and Refining Algorithms

Assignment and Comparison

Assignment stores a new value in a variable. A comparison asks a question about values and answers True or False, leaving everything as it was.

Assignment updates a variable

An assignment is written with a single =, with the variable name on the left and the value on the right. Python works out the right-hand side first, then stores the result, so whatever the variable held before is replaced. That is what makes it an update.

For example, coins = 8 stores 8 in coins. A later line coins = coins * 3 works out 24 and stores it, and the 8 has gone for good. The same variable now holds a different value.

Comparison asks a question

A comparison checks two values against each other and produces a Boolean, either True or False. Nothing is stored, so the variables keep the values they already had. Comparisons matter because the True or False they produce is what a condition uses to decide which path an algorithm takes.

OperatorMeaningExample when score holds 12Result
==equal toscore == 12True
!=not equal toscore != 12False
<less thanscore < 20True
>greater thanscore > 20False
<=less than or equal toscore <= 12True
>=greater than or equal toscore >= 15False

= assigns, == compares

The two are easy to mix up because they look so alike. A single = gives a variable a value; a double == asks whether two values are the same. A condition must be a question that produces True or False, so Python rejects an assignment used where a comparison is needed and reports a syntax error. Remembering that one symbol stores and two symbols ask keeps the two jobs apart.

energy = 50
energy = energy - 12       # assignment: energy now holds 38
print("Energy:", energy)
print(energy < 40)         # comparison: True, and energy is still 38
print("Energy:", energy)

Output:

Energy: 38
True
Energy: 38

Practise this

OCR GCSE Computer Science · Writing and Refining Algorithms