print(type(3.14))
<class 'float'>
We can also do negative numbers
print(type(-0.5))
<class 'float'>
or whole numbers with but with a
.0
at the end.
print(type(2.0))
<class 'float'>
Remember, Python stores
int
data differently than
float
.
So if you put a number and there is a
.
anywhere, it will store it as a
float
.
This
.
with a number is an instruction to Python to store it as a
float
.
print(type(2.))
<class 'float'>
Even though there is no
0
after the
.
, Python stores it as a
float
.
I can do arithmetic as well.
result = 5.0 + 5.0
print(result)
print(type(result))
10.0 <class 'float'>
Note that
answer
is still
10
, but now it is a
float
because my expression
5.0 + 5.0
uses
float
and not
int
.
Okay, but what if I do this.
result = 5 / 5
What would the type be? Well, let's find out.
print(type(result))
<class 'float'>
It is a
float
, why?
Well, the answer is that Python, and all programming languages, aim to be consistent and minimize surprizes.
If we were to perform the following division
result = 3.14159 / 52.910
print(result)
print(type(result))
0.059376110376110375 <class 'float'>
It is no surprise that this would be a
float
.
However, what if we mixed data types?
result = 3 / 52.910
Which data type should Python use?
print(result)
print(type(result))
0.056700056700056706 <class 'float'>
It is
float
!
If we rounded
0.059376110376110375
to be an
int
, this would be
0
, which we know it is not correct.
Thus, Python always errs on the side of caution and "upgrades"
int
values to
float
whenever there could be an issue—even if the result could technically be an
int
like in our
5 / 5
example.