Arithmetic Operators
When you do arithmetic in Python, the answer is not always a whole number. Every result has a type: either an integer (a whole number) or a real (a number with a decimal point, called a float in Python). Which one you get depends on the operator you use and on whether the values you start with are integers or reals.
The / operator always returns a real, even when the division works out exactly. 45 / 9 gives 5.0, not 5. Python writes the .0 to show the answer is a real, because a real is allowed to hold a fractional part even when this particular answer has not got one.
If both values are positive integers, then +, -, *, //, % and ** all give an integer result. The table shows some expressions and the type of each result, so you can see how the type changes.
| Expression | Result | Type of result | Why |
|---|---|---|---|
| 25 + 4 | 29 | integer | both values are integers |
| 25 // 4 | 6 | integer | both values are integers |
| 4 ** 3 | 64 | integer | both values are integers |
| 25 / 4 | 6.25 | real | / always gives a real |
| 45 / 9 | 5.0 | real | / always gives a real, even when it divides exactly |
| 25 + 1.5 | 26.5 | real | one of the values is a real |
| 16 * 0.5 | 8.0 | real | one of the values is a real |
If either value in an arithmetic operation is a real, the result is a real too, whichever operator you use. So 25 + 1.5 gives 26.5, and 16 * 0.5 gives 8.0 โ a whole-number value, but still a real because a real value was involved. When both values are positive integers, only / gives a real by itself; with the other operators you need at least one real value in the calculation before the answer becomes a real.
OCR GCSE Computer Science ยท Arithmetic Operators