Menu

Casting

Numeric Conversion

int() and float() are the Python functions that convert a value to an integer or to a real number.

Converting to an integer

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.

Converting to a real number

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.

Booleans, integers and real numbers

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.

valueint(value)float(value)
"42"4242.0
8.788.7
-8.7-8-8.7
151515.0
True11.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.

Practise this