This blog post is all about numeric data types—in other words, numbers. Python provides the following data types for working with numbers:
int(signed integers) – Whole numbers / Integersfloat– Floating-point numberscomplex– Complex numbers
I won’t go into detail about complex numbers here, as in practice, the focus is clearly on the int and float types.
int
The int data type includes positive and negative whole numbers:
>>> a = 10
>>> b = 2
>>> a + bAs the example shows, you can apply standard arithmetic operators. Interestingly, the result of a division is always of the type float:
>>> result = a / 2
5.0
>>> type(result)
<class 'float'>Converting from one numeric data type to another can be done like this:
# integer to float
>>> float(3)
3.0float
The float type is also pretty straightforward:
>>> a = 4.2
>>> b = 2.8
>>> a + b
7.0Converting from a float to an int simply truncates (removes) the decimal places. No rounding takes place:
>>> x = 14.9
>>> int(x)
14Instead, you can use the round() function to round numbers:
>>> x = 14.9
>>> round(x)
15In addition, there are several other useful functions available. For example, you can calculate powers using pow(). If you want to calculate 3 to the power of 4, it looks like this:
>>> pow(3, 4)
81The base (3) and the exponent (4) are passed as arguments to the pow() function. Alternatively, you can use the ** operator:
>>> 3**4
81You can calculate the square root using sqrt(). To do this, you first need to import the math module:
>>> from math import sqrt
>>> sqrt(4)
2.0The natural logarithm can be calculated using log():
>>> from math import log
>>> log(4)
1.3862943611198906You can find more functions in the Python documentation on mathematical functions.