Operator Precedence in Python

Part 1: What is Operator Precedence in Python?

  • As we know there is different kind of Operators.
  • Operator Precedence means the order in which the different Operators are evaluated.
  • We use multiple Operator in a single statement than they follow the Operator Precedence rule.
  • Example:
        Input:   20-3*5

        Step 1   3*5=15
        Step 2   20-15=5

        Output:   5
  • In Simple words Precedence means which operator will solved first.
  • Part 2: Operator precedence (High to low)

    Parentheses () Example :
    10-(3*5)
    3*5=15
    10-15
    -5
    Exponent Power, ** Example :
    100-(3**4)
    3**4=81
    100-81
    19
    Multiplication, Division, Integer Division, Modulus *, /, //, % Example :
    Addition, Subtraction +,- Example :
    Comparison Operator ==, !=, <, >, <=, >= Example :
    Logical Operator And, Or, Not Example :

    Part 3: How to learn in Easy way

    Part 3.1: Think About the Video Game

  • Step 1 = Power Up The Player
  • Step 2 = Super power Attack
  • Step 3 = Fight Enemies (*, /, //, %)
  • Step 4 = Collect points(+, -)
  • Step 5 = Compare points with another player

  • Part 3.2: Easy Trick: The BODMAS Rule

    B Brackets "(5-2)"
    O Order "5**2"
    D Division "5/2"
    M Multiple "5*2
    A Addition "5+2"
    S Subtraction "5-2"