Search⌘ K
AI Features

Numbers

Explore Python 3's native numeric types such as integers, floats, and fractions. Understand type checking, coercion between int and float, and numerical operations including division and powers. Learn how numeric values behave in boolean contexts and how to use Python's math and fractions modules effectively.

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.

Python 3.5
print (type(1)) #①
#<class 'int'>
print (isinstance(1, int) ) #②
#True
print (1 + 1 ) #③
#2
print (1 + 1.0 ) #④
#2.0
print (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.

Python 3.5
print (float(2) ) #①
#2.0
print (int(2.0)) #②
#2
print (int(2.5) ) #③
#2
print (int(-2.5) ) #④
#-2
print (1.12345678901234567890) #⑤
#1.1234567890123457
print (type(1000000000000000)) #⑥
#<class 'int'>

① You can explicitly coerce an int to a float by calling the float() function.

② Unsurprisingly, you can ...