GoConqr hat ein neues Design! Sag uns, wie es dir gefällt.

Modul 19 von 24 · Text

Operators and their priorities

David Khieu

Operators and their priorities

So far, we've treated each operator as if it had no connection with the others. Obviously, sich an ideal and simple situation is a rarity in real programming. 

Also, you will very often find more than one operator in one expression, and then this presumption is no longer so obvious. 

Consider the following expression: 

2+3*5

You probably remember from school that Multiplications preed additions. 

You surely remember that you should first multiply 3 by 5 and, keeping the 15 in your memory, then add it to 2, thus getting the result of 17. 

The phenomenon that causes some operators to act before others is known as the hierarchy of priorities. 

Python precisely defines the priorities of all operators, and assumes that operators of a larger (higher) priority perform their operations before the operators of a lower priority. 

So, if you know that * has a higher priority that +, the computation of the final result should be obvious. 

Operators and their bindings

The binding of the operator determines the order of computations performed by some operators with equal priority, put side by side in one expression. 

Most of Python's operators have left-sided binding, which means that the calculation of the expression is conducted from left to right. 

This simple example will show you how it works. Take a look:

print(9 % 6 % 2)

There are two possible ways of evaluating this expression: 

  • from left to right: first 9%6 gives 3, then then 3%2 gives 1
  • from right to left: first 6%2 gives 0, then 9%0 causes a fatal error. 

Run the example and see what you get. 

The result should be 1. This operator has left-sided binding. But there's one interesting exception. 

 

Anleitung

Um im Kurs weiterzukommen, sende einen Versuch dieses Quiz ab. Du kannst ihn nach der letzten Frage absenden.

Zum gewählten Modul

Feedback

Worum geht es?

Wie gefällt dir das neue Design?

Dein Eindruck