Operator Order

“Operator order” is just a fancy phrase I coined to describe how, similar to mathematical equations, there is a specific precedence when evaluating code. In maths there is a concept called BODMAS (brackets, orders, divide, multiplication, addition, subtraction). This concept states that in a mathematical equation, all equations must be carried out in the order of BODMAS; B –> O –> D –> M –> A –> S. The concept is also found in python and all mathematical equations and certain boolean conditions found in the code follow this concept.

[Console]

>>> False == False or True

>>> False == (False or True)

>>> (False == False) or True

=====

[Interpreter]

True

False

True

A mathematical example would follow as:

[Console]

>>> if 1 + 1 * 2 == 4:

print(“yes”)

else:

print(“no”)

=====

[Interpreter]

no

A more complicated example is as follows:

[Console]

>>> x = 4

>>> y = 2

>>> if not 1 + 1 == y or x == 4 and 7 == 8:

print(“Yes”)

elif x > y:

print(“No”)

=====

[Interpreter]

No

* This example is more complicated therefore I will work through the previous example below:

  1. The “AND” is taken into account first. Therefore  ” x == 4″ and “7 == 8” is evaluated first. This comes out to be FALSE due the combination of true and false statements.
  2. –> if not 1 + 1 == y or FALSE.
  3. The statement “1 + 1 == y” evaluates to TRUE.
  4. –> if not TRUE or FALSE = the “TRUE or FALSE” evaluates to TRUE
  5. –> if not TRUE
  6. –> if FALSE  = due to the presence of the “not”
  7. This means that the “FALSE” will cause the statement associated with the false to be rejected. As as result the ‘Elif” statement is accepted and consequently the answer is “no”.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s