Arithmetic operators in Python

In this post, let’s see how to perform simple calculations in the Python environment. Suppose we want to use the Python prompt as a simple calculator, then we will write:

>>> 6 + 5
11

Here we have visualized the result of an arithmetic operation: the sum of five and six. Python recognizes the numbers and the addition sign and adds them. Then show the result.

All arithmetic operators can be used:

  • addition (+)
  • subtraction (-)
  • multiplication (*)
  • division (/)

We can then combine different operations to get multiple expressions:

>>> ((5 * 4) + (6 – 3)) / (1 + 4)
4.6

In the expression we have just seen, it is possible to notice how Python uses parentheses to perform operations on numbers, these determine variations in the order in which they are performed.

Arithmetic operators in Python

Let’s see what happens if you write the same sequence without the brackets:

>>> 5 * 4 + 6 – 3/1 + 4
27.0

As you can see the result is quite different and depends on the fact that Python calculates the multiplications and divisions before the sums and subtractions, according to what is dictated by the rules imposed by the algebra.

These rules are imposed by all programming languages ​​and are used to determine the evaluation sequence of operations that goes by the name of precedence between operators.

Leave a Reply

Your email address will not be published. Required fields are marked *