Types of results
Every value has a type. The function type tells you which:
>>> type(7)
<class 'int'>
>>> type(7.0)
<class 'float'>
>>> type("7")
<class 'str'>Don't mind the word "class" for now; the part in quotes is the name of the type. So 7 is an integer, 7.0 is a float and "7" is a string.
The type of a result
What type a calculation gives depends on its operator and on its operands. Compare these:
>>> 2 + 3
5
>>> 2 + 3.0
5.0
>>> 6 / 3
2.0
>>> 7 // 2
3
>>> 7.5 // 2
3.0
>>> type(6 / 3)
<class 'float'>Look at them in pairs. 2 + 3 is the integer 5, but put the float 3.0 in place of 3 and the answer turns into the float 5.0, though it's still a whole number. 6 / 3 divides two integers evenly and still gives 2.0: division with / gives a float every time. 7 // 2 is the integer 3, and 7.5 // 2 rounds down as well, to 3.0, a float because a float went in.
The type shows in what you print, so choose the operator that gives the output you want:
minutes = 240
print(f"{minutes / 60} hours")
print(f"{minutes // 60} hours")
4.0 hours
4 hoursIn a real calculation, floats and integers mix freely. This program works out a car's fuel use per 100 kilometers:
liters = 42.5
kilometers = 680
per_100_km = liters / kilometers * 100
print(f"Fuel used: {per_100_km} liters per 100 km")
print(type(per_100_km))
Fuel used: 6.25 liters per 100 km
<class 'float'>Converting between types
The name of a type also works as a function that converts a value into that type. You've met str already; int and float work the same way:
>>> int(3.9)
3
>>> float(3)
3.0
>>> str(3.5)
'3.5'int doesn't round: it simply drops everything after the decimal point, so int(3.9) is 3.