Search code examples
pythonjupyter-notebookoperatorsoperator-precedence

Operation_Precedence_in_Python


Could someone explain to me about operator precedence? For eg. Modulo(%), integer division(//), exponential(**) What comes first, second, third and so on. Also please help me with the output of the following code and with step by step explanation:

print(8 % 3 ** 4 // 3 + 2)

I coudnt understand about Operator Precedence. Please help


Solution

  • This is the Operator Precedence from parentheses to logical or operator. if you have parentheses and logical or operator in your expression. parentheses will be evaluated first and logical or operator will be evaluated last due to order of operator precedence.

    Associativity is when you have operators of same precedence.then it evaluates from left to right . for example(2*3//3):if you have multiplication * and floor division // in your expression. then multiplication is evaluated first then it goes for floor division as they both have same precedence.it follows associativity evaluating from left to right.

    •   Operators   •   Meaning
    •   ()  •   Parentheses
    •   **  •   Exponent
    •   +x, -x, ~x  •   Unary plus, Unary minus, Bitwise NOT
    •   *, /, //, % •   Multiplication, Division, Floor division, Modulus
    •   +, -    •   Addition, Subtraction
    •   <<, >>  •   Bitwise shift operators
    •   &   •   Bitwise AND
    •   ^   •   Bitwise XOR
    •   |   •   Bitwise OR
    •   ==, !=, >, >=, <, <=, is, is not, in, not in    •   Comparisons, Identity, Membership operators
    •   not •   Logical NOT
    •   and •   Logical AND
    •   or  •   Logical OR
    
    
    
    
    print(8 % 3 ** 4 // 3 + 2)---exponent is evaluated first 
    print(8%81//3+2)----modulo and floor division have same precedence.so it evaluates from left to right . first evaluates modulo.
    print(8//3+2)----then goes for floor division 
    print(2+2)-----then addition operation
    so the output is 4.