As you saw in the final section of the previous tutorial on numeric expressions in Python, Fractions, the following two expressions give different answers:
18.0 / 7.0
# This returns 2.571485714285716
18 / 7
# This returns 2
So what’s going on here? Well, this is an example of the two main number systems in Python, integers and floats.
A float can be distinguished from an integer because it has a fractional part, even if it is just .0, such as the .0 at the end of the 18 and 7 in the above example.
If you choose to leave out the fractional portion of a set of numbers, Python will always return it as an integer, unless you force it to return it as a float which I will explain in a moment.
If you put in the fractional part, even if it is just a 0, Python will always return it as a float, unless you force it to do otherwise.
Now what happens if you use both a float and an int? Such as 18 / 7.0?
Let’s try it and find out.
18 / 7.0
# I get the same as 18.0 / 7.0
Why does it do this?
By using a float with an integer, Python defaults to a float for the result.
Forcing a Number Type in Python
Forcing a number to be either an integer or a float is a pretty simple task. All you have to do is add the following to your expressions:
int (18.0 / 7.0)
# This will force Python to return an integer value
# instead of the default float.
float (18 / 7)
# This will force Python to return a float value
# instead of the default integer.
If you need to determine what number type something is, this can be determined very easily with the following function:
# This will return <type ‘int’>
# In other words, 18 is an integer.
# This will return <type ‘float’>
# So, 18.0 is a float.
If you convert a floating point number to an integer, the fraction is lost, so if you need to use it, it is a good idea to keep your numbers in the floating point format.
Does 1 = 1.0?
You would expect 1 and 1.0 to be the same, and logically, they are, right?
While the integer 1 is numerically the same as 1.0, their value is not equal. You can test this in Python by doing the following:
1 == 1.0
# This asks Python if 1 is exactly equal to 1.0
# It returns True.
1 is 1.0
# This asks Python if 1 and 1.0 hold the same value.
# It returns False.
Floating point numbers are encoded as finite approximations in binary. This can cause some slight rounding inaccuracies to occur that are machine based.
Have a look below at some examples:
1.0 / 3.0
# Python cannot encode the infinite fraction, try it and see.
(0.1 * 3.0) / 0.1
# This should return 3.0, I do not get exactly that though.
# Try it and see what you get. It will be 3.something.
If you have any comments thus far, please let me know, the same goes if you have any corrections or input for the tutorials.
Next up I will be looking at strings in Python, so stay tuned.