Skip to main content

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-pointThe 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 (/).

# Basic operations with numbers in Python
>>> 1+2
3
>>> 3.0-2
1.0
>>> 2*3
6
>>> 6/2
3.0

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 integerIn 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.

>>> 10%2
0

Power is calculated in Python with a double asterisk (**). In this case, we can say, for example, that 2 raised to 4 is 16.

>>> 2**4
16 Additional resources: Convert int to string

 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 moduleWith the math module, we can also make use of mathematical constants such as the number pi or the number e.

>>> import math
>>> math.sqrt(16)
4.0
>>> math.sin(math.pi/2)
1.0
>>> math.log(math.e)

Comments

Popular posts from this blog

Getting Started with python

5 harmless ways to kick spam out of your blog