Numbers in Python
Numbers in Python
In Python, there are two types of data that allow us to work with numbers. These data types are integers and floating-point. The difference between the two lies in the fact that floating-point numbers support decimals, while integers do not. Thus, we can say that the number 10 is of the integer type, but that 10.0 is floating-point since it has a decimal (even if this is 0).
Operations
With numbers, we can perform operations as if Python were a simple calculator. To begin we have the four basic operations that are: addition (+), subtraction (-), multiplication (*), and division (/).
We can see that the result of an addition, subtraction, or multiplication of two whole numbers is another whole number. But if one of the numbers is floating-point the result is also floating-point.
In the case of division, the data type of the result varies depending on the version of Python that we use. In a previous article, we have already seen that in Python 2 the division between integers is another integer. In contrast, in Python 3 the result of a division (as in the previous example) is always floating-point.
Other basic operations that we can perform are the module and the power. The module consists of obtaining the remainder of a division. So, we say that the result of the operation 10 mod 3 is 1 since 3 * 3 + 1 = 10. This operation is performed in Python with the percent symbol (%). One of the uses of this operation is to check if a number is odd or even. If the number is even, then its modulus two is zero.
Power is calculated in Python with a double asterisk (**). In this case, we can say, for example, that 2 raised to 4 is 16.
Working with the math module
In addition, we can perform other mathematical operations such as the square root, logarithms, trigonometric functions, etc. using the functions available in the Python math module. With the math module, we can also make use of mathematical constants such as the number pi or the number e.
Comments
Post a Comment