Order of Operations

When more than one operator appears in an expression, the order of evaluation depends on the rule of precedence. For mathematical operators, Python follows mathematical convention. There is PEMDAS acronym and its useful way to remember the rules:
Parentheses have the highest precedence and can be used to force an expression to evaluate in order you want. Since expressions in parenthesis are evaluated first. For example
>>> 2*(3-1)
4
>>>(1+1)**(2+2)
16
You can also use parentheses to make an expressions easier to read, as for example:
>>> minutes = 4 
>>>(minutes * 100)/60.0 
6.66666667
>>>minutes*100/60.0 
6.66666667
As you can see from previous example the parenthesis are used for easier reading because the use of parenthesis in this case don’t change the result.
Exponentiation has the next highest precedence
>>>2**1+1
3 
The result is 3 not 4 because the exponentiation has higher precedence then addition operator.
 >>>3*1**3
3 
The result is 3 not 27 because exponentiation has higher precedence than multiplication operator.
Multiplication and Division have the same precedence, which is higher than Addition and Subtraction, which also have the same precedence. So
>>>5*3-1
14 
The result is 14 not 10 because the multiplication has higher precedence than subtraction.
>>>6+6/2
9 
The result is 9 not 6 because the division has higher precedence than addition.
Addition and Subtraction has lowest precedence and are evaluated from left to right.
>>>5-3-1
1

The result is 1 not 3 because the 5-3 happens first and then 1 is subtracted from 2. 

Nema komentara:

Objavi komentar