Mastering Python Operators, Expressions, and Precedence: A Comprehensive Guide to Writing Efficient Code

In Python, operators are symbols that perform operations on variables and values. An expression is a combination of variables, values, and operators that computes to a value. Operators are fundamental to writing logic in programming.

Types of Operators in Python:

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators

Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication, division, etc.

OperatorNameDescriptionExampleResult
+AdditionAdds two operands5 + 38
-SubtractionSubtracts the second operand from the first5 - 32
*MultiplicationMultiplies two operands5 * 315
/DivisionDivides the first operand by the second5 / 22.5
%ModulusReturns the remainder of the division5 % 21
**ExponentiationRaises the first operand to the power of the second2 ** 38
//Floor DivisionDivides the first operand by the second and rounds down5 // 22

Examples:

a = 10
b = 3

addition = a + b # 13
subtraction = a - b # 7
multiplication = a * b # 30
division = a / b # 3.3333333333333335
modulus = a % b # 1
exponentiation = a ** b # 1000
floor_division = a // b # 3

Comparison Operators

Comparison operators are used to compare two values and return a boolean value (True or False).

OperatorNameDescriptionExampleResult
==Equal toReturns True if both operands are equal5 == 3False
!=Not equal toReturns True if both operands are not equal5 != 3True
>Greater thanReturns True if the first operand is greater than the second5 > 3True
<Less thanReturns True if the first operand is less than the second5 < 3False
>=Greater than or equal toReturns True if the first operand is greater than or equal to the second5 >= 3True
<=Less than or equal toReturns True if the first operand is less than or equal to the second5 <= 3False

Examples:

a = 5
b = 3

equal = a == b # False
not_equal = a != b # True
greater_than = a > b # True
less_than = a < b # False
greater_equal = a >= b # True
less_equal = a <= b # False

Logical Operators

Logical operators are used to combine conditional statements. They are primarily used to evaluate multiple expressions together.

OperatorNameDescriptionExampleResult
andLogical ANDReturns True if both expressions are True(5 > 3) and (3 > 1)True
orLogical ORReturns True if at least one of the expressions is True(5 > 3) or (3 < 1)True
notLogical NOTReverses the result of the expression; returns False if the expression is Truenot(5 > 3)False

Examples:

a = True
b = False

and_operator = a and b # False
or_operator = a or b # True
not_operator = not a # False

Bitwise Operators

Bitwise operators perform operations on the binary representations of integers. They are typically used in low-level programming, such as working with device drivers or system kernels.

OperatorNameDescriptionExampleResult
&Bitwise ANDPerforms a logical AND operation on each pair of corresponding bits5 & 31 (0101 & 0011 = 0001)
``Bitwise ORPerforms a logical OR operation on each pair of corresponding bits`5
^Bitwise XORPerforms a logical XOR operation on each pair of corresponding bits5 ^ 36 (0101 ^ 0011 = 0110)
~Bitwise NOTInverts all the bits in the operand (bitwise complement)~5-6 (NOT 0101 = 1010, which is -6 in 2’s complement)
<<Left ShiftShifts the bits of the operand to the left by the specified number of positions5 << 110 (0101 << 1 = 1010)
>>Right ShiftShifts the bits of the operand to the right by the specified number of positions5 >> 12 (0101 >> 1 = 0010)

Examples:

a = 5  # 0101 in binary
b = 3 # 0011 in binary

bitwise_and = a & b # 1 (0001 in binary)
bitwise_or = a | b # 7 (0111 in binary)
bitwise_xor = a ^ b # 6 (0110 in binary)
bitwise_not = ~a # -6 (inverted bits of 0101 give 1010 in binary, which is -6 in two's complement)
left_shift = a << 1 # 10 (1010 in binary)
right_shift = a >> 1 # 2 (0010 in binary)

Assignment Operators

Assignment operators are used to assign values to variables. In addition to basic assignment, Python also provides compound assignment operators that combine an arithmetic operation with assignment.

OperatorNameDescriptionExampleResult (after)
=AssignAssigns the value of the right operand to the left operanda = 5a is 5
+=Add and assignAdds the right operand to the left operand and assigns the result to the left operanda += 3a becomes 8
-=Subtract and assignSubtracts the right operand from the left operand and assigns the result to the left operanda -= 3a becomes 2
*=Multiply and assignMultiplies the left operand by the right operand and assigns the result to the left operanda *= 3a becomes 15
/=Divide and assignDivides the left operand by the right operand and assigns the result to the left operanda /= 3a becomes 5.0
%=Modulus and assignTakes modulus using two operands and assigns the result to the left operanda %= 3a becomes 2
**=Exponent and assignRaises the left operand to the power of the right operand and assigns the result to the left operanda **= 3a becomes 125
//=Floor divide and assignFloor divides the left operand by the right operand and assigns the result to the left operanda //= 3a becomes 5
&=Bitwise AND and assignPerforms a bitwise AND operation between the two operands and assigns the result to the left operanda &= 3a becomes 1
`=`Bitwise OR and assignPerforms a bitwise OR operation between the two operands and assigns the result to the left operand`a
^=Bitwise XOR and assignPerforms a bitwise XOR operation between the two operands and assigns the result to the left operanda ^= 3a becomes 4
<<=Left shift and assignShifts the bits of the left operand to the left by the number of positions specified by the right operand and assigns the result to the left operanda <<= 1a becomes 10
>>=Right shift and assignShifts the bits of the left operand to the right by the number of positions specified by the right operand and assigns the result to the left operanda >>= 1a becomes 2

Examples:

a = 5
a += 2 # a becomes 7
a *= 3 # a becomes 21
a //= 2 # a becomes 10
a **= 2 # a becomes 100

Operator Precedence

Operator precedence determines the order in which operations are performed in an expression with multiple operators. Operators with higher precedence are executed before operators with lower precedence. If operators have the same precedence, their associativity (left-to-right or right-to-left) determines the order of operations.

Python Operator Precedence Table:

PrecedenceOperatorDescription
1()Parentheses
2**Exponentiation
3+x, -x, ~xUnary plus, Unary minus, Bitwise NOT
4*, /, //, %Multiplication, Division, Floor Division, Modulus
5+, -Addition, Subtraction
6<<, >>Left Shift, Right Shift
7&Bitwise AND
8^Bitwise XOR
9``
10in, not in, is, is not, <, <=, >, >=, ==, !=Comparisons, Membership, Identity
11notLogical NOT
12andLogical AND
13orLogical OR
14if ... elseConditional Expression (Ternary)
15= , +=, -=, *=, /=, %=, &=, `=, ^=, >>=, <<=, **=, //=, :=`

Examples:

result = 2 + 3 * 4  # 14 (Multiplication before addition)
result = (2 + 3) * 4 # 20 (Parentheses change precedence)
result = 2 ** 3 ** 2 # 512 (Exponentiation is right-associative)
result = 2 + 3 * 4 > 15 and not False # True (Combines arithmetic, comparison, and logical operators)

Understanding operator precedence is crucial for writing correct and efficient expressions in Python. It’s always a good practice to use parentheses to make your expressions clear, especially when the default precedence rules might not align with your intentions.

Click here to Download Python

Let’s delve deeper into the concept of operator precedence in Python, especially focusing on how expressions with multiple operators are evaluated.

Operator Precedence in Expressions

When you write an expression with multiple operators, Python determines the order in which the operations are performed based on operator precedence. Operators with higher precedence are executed before operators with lower precedence. If two operators have the same precedence, Python evaluates the expression based on their associativity—which can be left-to-right or right-to-left.

Associativity of Operators

  • Left-to-Right Associativity: Most operators, including arithmetic, bitwise, and logical operators, are evaluated from left to right when they have the same precedence level.
  • Right-to-Left Associativity: Operators like exponentiation (**) and assignment operators (=, +=, etc.) are evaluated from right to left.

Examples of Operator Precedence with Multiple Operators

Arithmetic Operators

Consider the following expression:

result = 2 + 3 * 4

  • Step 1: Identify the operators and their precedence:
    • + (Addition) has lower precedence than * (Multiplication).
  • Step 2: Evaluate the expression based on precedence:
    • Multiplication (*) is performed first: 3 * 4 = 12.
    • Then, addition (+) is performed: 2 + 12 = 14.
  • Final Result: result = 14.

Mixed Operators with Parentheses

result = (2 + 3) * 4

  • Step 1: Identify the parentheses:
    • Parentheses have the highest precedence, so the expression inside them is evaluated first.
  • Step 2: Evaluate the expression:
    • First, addition (+) inside the parentheses: 2 + 3 = 5.
    • Then, multiplication (*) outside the parentheses: 5 * 4 = 20.
  • Final Result: result = 20.

Exponentiation and Multiplication

result = 2 ** 3 ** 2

  • Step 1: Identify the operators and their precedence:
    • Both ** operators have the same precedence and are right-associative.
  • Step 2: Evaluate from right to left:
    • First, the rightmost exponentiation: 3 ** 2 = 9.
    • Then, the leftmost exponentiation: 2 ** 9 = 512.
  • Final Result: result = 512.

Combining Arithmetic, Comparison, and Logical Operators

result = 2 + 3 * 4 > 15 and not False

Step 1: Identify the operators and their precedence:

  • * (Multiplication) has higher precedence than + (Addition).
  • > (Comparison) is evaluated after arithmetic operations.
  • and and not (Logical operators) have lower precedence but will be evaluated according to their own precedence rules.

Step 2: Evaluate the expression:

  • First, multiplication: 3 * 4 = 12.
  • Then, addition: 2 + 12 = 14.
  • Next, comparison: 14 > 15 = False.
  • Then, logical NOT: not False = True.
  • Finally, logical AND: False and True = False.

Final Result: result = False.

Detailed Operator Precedence Table with Associativity

Here’s a table summarizing operator precedence and associativity:

PrecedenceOperatorDescriptionAssociativity
1()ParenthesesN/A
2**ExponentiationRight-to-Left
3+x, -x, ~xUnary plus, Unary minus, Bitwise NOTRight-to-Left
4*, /, //, %Multiplication, Division, Floor Division, ModulusLeft-to-Right
5+, -Addition, SubtractionLeft-to-Right
6<<, >>Left Shift, Right ShiftLeft-to-Right
7&Bitwise ANDLeft-to-Right
8^Bitwise XORLeft-to-Right
9``Bitwise OR
10in, not in, is, is not, <, <=, >, >=, ==, !=Comparisons, Membership, IdentityLeft-to-Right
11notLogical NOTRight-to-Left
12andLogical ANDLeft-to-Right
13orLogical ORLeft-to-Right
14if ... elseConditional Expression (Ternary)Right-to-Left
15= , +=, -=, *=, /=, %=, &=, `=, ^=, >>=, <<=, **=, //=, :=`Assignment Operators

Key Points to Remember

  • Parentheses are your best friend when dealing with complex expressions. They override the default precedence and make your intentions clear.
  • Right-to-Left associativity is uncommon and mainly found in operators like exponentiation and assignment.
  • Left-to-Right associativity is the norm for most other operators, including arithmetic, bitwise, and logical operators.

Understanding operator precedence and associativity ensures that your expressions are evaluated as intended, avoiding unexpected results.