Home | | Problem Solving and Python Programming | Operator Precedence - Python

Chapter: Problem Solving and Python Programming : Data, Expressions, Statements

Operator Precedence - Python

When an expression contains more than one operator, the order of evaluation depends on the order of operations.

OPERATOR PRECEDENCE:


When an expression contains more than one operator, the order of evaluation depends on the order of operations.


-For mathematical operators, Python follows mathematical convention.

 

-The acronym PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition, Subtraction) is a useful way to remember the rules:

 

v   Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1)is 4, and (1+1)**(5-2) is 8.

 

v   You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even if it doesn’t change the result.

 

v   Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2 *3**2 is 18, not 36.

 

v   Multiplication and Division have higher precedence than Addition and Subtraction. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.

 

v   Operators with the same precedence are evaluated from left to right (except exponentiation).

 

Example:

 

a=9-12/3+3*2-1

a=?

a=9-4+3*2-1

a=9-4+6-1

a=5+6-1

a=11-1

a=10

 

A=2*3+4%5-3/2+6

A=6+4%5-3/2+6

A=6+4-3/2+6

A=6+4-1+6

A=10-1+6

A=9+6

A=15

 

find m=?

m=-43||8&&0||-2

m=-43||0||-2

m=1||-2

m=1

 

a=2,b=12,c=1

d=a<b>c

d=2<12>1

d=1>1

d=0

 

a=2,b=12,c=1

d=a<b>c-1

d=2<12>1-1

d=2<12>0

d=1>0

d=1

 

a=2*3+4%5-3//2+6

a=6+4-1+6

a=10-1+6

a=15

 

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Problem Solving and Python Programming : Data, Expressions, Statements : Operator Precedence - Python |

Related Topics

Problem Solving and Python Programming : Data, Expressions, Statements


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.