Casting
int() and float() are the Python functions that convert a value to an integer or to a real number.
int() converts a valid whole-number string, such as "42", or a real number into an integer. When you pass it a real number, the fractional part is removed by truncation towards zero, which is not the same as rounding. For example, int(8.7) gives 8 and int(-8.7) gives -8, because both values move towards zero. So 8.7 does not become 9; if that was your intention you would need round() instead.
float() converts a valid numeric string, such as "3.25", or an integer into a real number. float(6) gives 6.0, which is a real number that happens to have nothing after the point. You use it when a value needs to keep its decimal part, such as a price in pounds and pence or a measured length in metres.
Boolean values convert to integers too: int(True) gives 1 and int(False) gives 0, because a Boolean is stored as 1 or 0, with 1 meaning True and 0 meaning False. In the other direction, an integer becomes a real number with float(), and a real number becomes an integer with int(), losing the fractional part as described above.
| value | int(value) | float(value) |
|---|---|---|
| "42" | 42 | 42.0 |
| 8.7 | 8 | 8.7 |
| -8.7 | -8 | -8.7 |
| 15 | 15 | 15.0 |
| True | 1 | 1.0 |
# truncating a real number towards zero
race_time = 47.62
whole_minutes = int(race_time)
print(whole_minutes)
# turning an integer into a real number
runners = 12
runners_as_real = float(runners)
print(runners_as_real)
# a Boolean becomes 1 or 0
finished = int(True)
print(finished)Output:
47
12.0
1
Both functions return a new value rather than changing the one you give them, so race_time still holds the real number while whole_minutes holds the integer.
Edexcel GCSE Computer Science · Casting