Numbers
We'll cover the following...
Numbers are awesome. There are so many to choose from. Python supports both integers and floating point numbers. There’s no type declaration to distinguish them; Python tells them apart by the presence or absence of a decimal point.
print (type(1)) #①#<class 'int'>print (isinstance(1, int) ) #②#Trueprint (1 + 1 ) #③#2print (1 + 1.0 ) #④#2.0print (type(2.0))#<class 'float'>
① You can use the type()
function to check the type of any value or variable. As you might expect, 1
is an int
.
② Similarly, you can use the isinstance()
function to check whether a value or variable is of a given type.
③ Adding an int
to an int
yields an int
.
④ Adding an int
to a float
yields a float
. Python coerces the int
into a float
to perform the addition, then returns a float
as the result.
Coercing Integers To Floats And Vice-Versa
As you just saw, some operators (like addition) will coerce integers to floating point numbers as needed. You can also coerce them by yourself.
print (float(2) ) #①#2.0print (int(2.0)) #②#2print (int(2.5) ) #③#2print (int(-2.5) ) #④#-2print (1.12345678901234567890) #⑤#1.1234567890123457print (type(1000000000000000)) #⑥#<class 'int'>
① You can explicitly coerce an int
to a float
by calling the float()
function.
② Unsurprisingly, you can ...