Operation precedence in python

Helenjoy
2 min readMay 21, 2023

--

The order of operations (also called precedence) of Python math operators is similar to that of mathematics.

The ** operator is evaluated first;

The *, /, //, and % operators are evaluated next, from left to right;

the + and — operators are evaluated last (also from left to right).

You can use parentheses to override the usual precedence if you need to.

Whitespace in between the operators and values doesn’t matter for Python (except for the indentation at the beginning of the line),

but a single space is convention.

Some examples:

>>> 2 + 3 * 6

20

>>> (2 + 3) * 6

30

>>> 48565878 * 578453

28093077826734

>>> 2 ** 8

256

>>> 23 / 7

3.2857142857142856

>>> 23 // 7

3

>>> 23 % 7

2

>>> 2 + 2

4

>>> (5–1) * ((7 + 1) / (3–1))

16.0

trying varoius operations in python

When we enter a code in python it tries to evaluate and make it to single value by using the set of rules given to it. The rules are to put the operators and values together to form the expression in a refined way just like our mathematics teacher helped us to solve equations with BODMAS rule. The teacher will put a cross if we break the rule ,same in case of python too ..

As we ask the teacher

If the expressions are not fed to it properly it throw an error “a syntax error. Its as simple as we as out math teacher if she writes some incomplete or wrong question in board.

For instance

>> 5 +

File “<stdin>”, line 1

5 +

^

SyntaxError: invalid syntax

>>> 42 + 5 + * 2

File “<stdin>”, line 1

42 + 5 + * 2

^

SyntaxError: invalid syntax

Errors to learn..

Errors are normal, it won’t break your computer, but you be ready to break your head and solve .

Believe it or not, even great programmers get errors. Normalize it. Happy learning ..

--

--

Helenjoy

Research aspirant in deep learning based video compression