Writing and Refining Algorithms
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.
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.
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.
| Operator | Meaning | Example when score holds 12 | Result |
|---|---|---|---|
== | equal to | score == 12 | True |
!= | not equal to | score != 12 | False |
< | less than | score < 20 | True |
> | greater than | score > 20 | False |
<= | less than or equal to | score <= 12 | True |
>= | greater than or equal to | score >= 15 | False |
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 OCR GCSE Computer Science · Writing and Refining Algorithms
OCR GCSE Computer Science · Relational Operators
OCR GCSE Computer Science · Variables