Loop Control Statements in C Introduction to HTML How to use the Github API The image tag, anchor tag and the button tag Ordered and Unordered Lists in HTML The division tag HTML Forms Tables in HTML Introduction to C Programming Introduction to Python Varibles and Datatypes in Python Operators in Python Typecasting in Python Input and Output in Python If Else in Python Loops in Python Break, Continue and Pass in Python Python practice section 1 Lists in Python Tuple in Python

Precedence of Operators in Python

When multiple operators are used in one expression such as +,-, **, or ^, etc, we need to decide the order in which to evaluate different operators on the basis of priority in order to get the correct results.

Python Operator Precedence Table

Precedence Operator Description Associativity
Highest ( ) Parentheses (grouping) Not Applicable
[ ] List indexing Not Applicable
f"[...]" String formatting (f-strings) Not Applicable
... ** ... Exponentiation Right to left
+x, -x Unary plus, Unary minus Not Applicable
~x Bitwise NOT Not Applicable
Higher *, /, % Multiplication, Division, Modulus Left to right
// Floor division (integer division) Left to right
+, - Addition, Subtraction Left to right
<<, >> Bitwise shift operators Left to right
& Bitwise AND Left to right
^ Bitwise XOR Left to right
| Bitwise OR Left to right
<, <=, >, >= Comparison operators Left to right
==, != Equality operators Left to right
not x Boolean NOT Not Applicable
and Boolean AND Left to right
or Boolean OR Left to right
Lowest =, +=, -=, ... Assignment operators Right to left

Example


# Operator precedence example

x = 10 + 5 * 2  # Multiplication has higher precedence than addition
print(x)  # Output: 20

y = (10 + 5) * 2  # Parentheses enforce higher precedence for addition
print(y)  # Output: 30

z = 10 - 5 / 2  # Division has higher precedence than subtraction
print(z)  # Output: 7.5

w = 10 - (5 / 2)  # Parentheses enforce higher precedence for division
print(w)  # Output: 7.5

a = 2 ** 3 ** 2  # Exponentiation right-to-left associativity
print(a)  # Output: 512

b = (2 ** 3) ** 2  # Parentheses enforce higher precedence for exponentiation
print(b)  # Output: 64

Output

20
30
7.5
7.5
512
64