Casting
When an expression contains a cast, work through it in a fixed order: work out the cast first to produce a value of the new data type, then apply the operator using those resulting data types. The cast has to come first because an operator behaves differently depending on the types it is handed.
Take int("15") + 5. The cast is worked out first, turning the text into the integer 15. The expression is now 15 + 5, so both values are integers and + adds them to give 20. Leave the cast out and "15" + 5 tries to combine text with a number, which is not allowed, so the program stops with an error.
The same order applies to str(). In str(9) + " lives" the cast runs first and gives the string "9". Both values are now strings, so + joins them into "9 lives" instead of adding anything.
| Expression | Cast worked out first | What the operator then works on | Result |
|---|---|---|---|
int("23") - 6 | 23 | 23 - 6 (two integers) | 17 |
float("0.75") * 8 | 0.75 | 0.75 * 8 (a real and an integer) | 6.0 |
str(9) + " lives" | "9" | "9" + " lives" (two strings) | "9 lives" |
One expression can hold more than one cast. In int("6") + float("2.25") each cast is worked out first, giving an integer 6 and a real 2.25. Adding an integer and a real gives a real, so the answer is 8.25.
# Each cast is worked out first, then the operator is applied
cost = int("7") * 5
print(cost)
label = str(3) + "rd"
print(label)
share = float("9") / 2
print(share)Output:
35
3rd
4.5 OCR GCSE Computer Science · Casting