A float is a Python number that can have a decimal part. The values 1 and 1.0 look similar, but 1 is an integer and 1.0 is a float. Both can take part in arithmetic. section 5.2
A few rules help you predict the result of a calculation:
- Dividing two integers with / produces a float: 3 / 2 gives 1.5. section 5.3
- Mixing an integer and a float in arithmetic produces a float: 3 + 2.0 gives 5.0. section 5.3
- float(4) gives 4.0. Converting the other way with int(3.94) gives 3: int() removes the decimal part rather than rounding it. section 5.3
Table 5.1. Mathematical operations on ints and floats and the resulting types
| Operation(s) |
Type of second object |
Type of result |
Example |
||
|---|---|---|---|---|---|
| int | + - * ** % | int | int | 3 + 2 3 - 2 3 * 2 3 ** 2 3 % 2 | gives 5 gives 1 gives 6 gives 9 gives 1 |
| int | / | int | float | 3 / 2 | gives 1.5 |
| int | + - * / ** % | float | float | 3 + 2.0 3 - 2.0 3 * 2.0 3 / 2.0 3 ** 2.0 3 % 2.0 | gives 5.0 gives 1.0 gives 6.0 gives 1.5 gives 9.0 gives 1.0 |
| float | + - * / ** % | int | float | 3.0 + 2 3.0 - 2 3.0 * 2 3.0 / 2 3.0 ** 2 3.0 % 2 | gives 5.0 gives 1.0 gives 6.0 gives 1.5 gives 9.0 gives 1.0 |
| float | + - * / ** % | float | float | 3.0 + 2.0 3.0 - 2.0 3.0 * 2.0 3.0 / 2.0 3.0 ** 2.0 3.0 % 2.0 | gives 5.0 gives 1.0 gives 6.0 gives 1.5 gives 9.0 gives 1.0 |
Use the operation table to check result types when you combine integers and floats. section 5.3
Convert minutes to hours and minutes
For 123 minutes, 123 / 60 gives 2.05 hours. int(2.05) gives 2 whole hours. Subtracting 2 leaves 0.05; multiplying that decimal part by 60 should give 3 minutes. Floats can store an approximation rather than the exact decimal value, so the calculation may produce a value just below 3. Use round((2.05 - 2) * 60) to get the intended whole-minute result. section 6.3 section 6.4



















