Precedence of Operators in Python: Complete Guide with Examples

Updated on 26/08/202522,320 Views

What's the answer to 2 + 3 * 4? Is it 20 or 14? If you're not sure, you've just discovered why understanding operator precedence is crucial. Python, like all programming languages, has a strict set of rules that decide which operation to perform first, ensuring that every expression has only one correct answer. 

These rules are known as the precedence of operators in Python. This tutorial will break down this "order of operations" for you, from arithmetic to logical operators. We'll also cover associativity, the tie-breaker rule, and provide a handy chart to make it all crystal clear. And if you are just starting your journey in programming, don't forget to explore our Data Science Courses and Machine Learning Courses to build a solid foundation. 

What is Precedence of Operators in Python?

Operator precedence in Python determines the order in which different operators are evaluated in an expression. For example, when you write an expression like 3 + 4 * 2, the multiplication (*) happens first, because it has higher precedence than addition (+).

In simple terms, operator precedence helps Python decide which operation to perform first when multiple operators are used in a single expression. This ensures your expressions are evaluated consistently and correctly.

If you don’t specify the order using parentheses, Python will follow the predefined rules of precedence, ensuring operations like multiplication, division, and subtraction happen before addition.

If you're exploring Python through basic exercises and want to see how it's used in real-world data science problems, consider learning more through a structured program in Data Science and Machine Learning.

Order of Precedence of Operators in Python

To help you understand operator precedence in Python with examples, here's a simple table showing the order in which Python evaluates operators.

The higher the operator is on the list, the higher its precedence.

Operator

Description

()

Parentheses (highest precedence)

+x, -x, ~x

Unary plus, Unary minus, Bitwise NOT

****, *

Exponentiation, Multiplication, Division

+, -

Addition, Subtraction

>>, <<

Bitwise right and left shift

&

Bitwise AND

^

Bitwise XOR

|

Bitwise OR

==, !=, >, <, >=, <=

Comparison operators

=, +=, -=, *=, /=

Assignment operators (lowest precedence)

Knowing this precedence of arithmetic operators in Python allows you to predict how your expressions will be evaluated.

If you want to override the default order, just use parentheses () to make the evaluation clear.

Python Precedence Order Rule - PEMDAS

When dealing with operator precedence in Python with examples, it’s helpful to remember the PEMDAS rule. This acronym stands for Parentheses, Exponents, Multiplication and Division (from left to right), Addition and Subtraction (from left to right). This is the order Python follows when evaluating expressions.

Here’s how it works:

  1. Parentheses (): Anything inside parentheses is evaluated first, no matter what.
  2. **Exponents **: Then, exponentiation (**) happens next.
  3. Multiplication (*) and Division (/): After that, multiplication and division are evaluated from left to right.
  4. Addition (+) and Subtraction (-): Finally, addition and subtraction are performed from left to right.

For example, in the expression 2 + 3 * 4, Python first evaluates 3 * 4 (multiplication) and then adds 2 to the result, following the PEMDAS rule.

If you need to change the order, just use parentheses to make the logic explicit.

Also Read: List of Operators In SQL [With Examples]

Associativity Rule for Operator Precedence in Python

The Associativity Rule in Python determines the order in which operators of the same precedence level are evaluated.

There are two types of associativity:

  1. Left-to-Right (LTR) Associativity: Most operators in Python, such as addition, subtraction, multiplication, and comparison operators, follow left-to-right associativity. This means Python evaluates the leftmost operator first.For example, in the expression 5 - 3 - 2, Python evaluates it as (5 - 3) - 2, going from left to right.
  2. Right-to-Left (RTL) Associativity: Some operators, like exponentiation (**), have right-to-left associativity. This means Python evaluates the rightmost operator first.For example, in 2 ** 3 ** 2, Python evaluates it as 2 ** (3 ** 2), meaning it performs 3 ** 2 first, and then raises 2 to the result.

These concepts will help you write more accurate and reliable code.

Examples of Comparison Operators

In Python, comparison operators are used to compare two values. These operators return either True or False based on the comparison.

Understanding operator precedence in Python with examples is key, as comparison operators have their own precedence when used with other operators in expressions.

Let's go through the comparison operators in Python:

1. Equal to (==)

This operator checks if two values are equal.

Example:

x = 5 + 2 
y = 3 * 2 + 1 
result = x ==
print(result)

Output:

True

Here, x becomes 7 (5 + 2), and y also evaluates to 7 (3 * 2 + 1), so x == y returns True.

2. Not equal to (!=)

This operator checks if two values are not equal.

Example:

a = 10 - 3 
b = 5 * 2 
result = a !=
print(result)

Output:

False

Here, a is 7 (10 - 3), and b is also 10 (5 * 2), so a != b evaluates to False.

3. Greater than (>)

This operator checks if the value on the left is greater than the value on the right.

Example:

x = (3 + 2) * 2
y = 10
result = x > y
print(result)

Output:

True

Here, x becomes 10 ((3 + 2) * 2), and y is also 10. The comparison x > y returns False because they are equal, so it will evaluate as False.

4. Less than (<)

This operator checks if the value on the left is less than the value on the right.

Example:

x = 8 - 3 * 2
y = 6
result = x < y
print(result)

Output:

True

In this case, the multiplication happens first (3 * 2 = 6), so x becomes 2 (8 - 6). Since 2 is indeed less than 6, the result is True.

5. Greater than or equal to (>=)

This operator checks if the value on the left is greater than or equal to the value on the right.

Example:

a = 6 + 4 * 3
b = 18
result = a >= b
print(result)

Output:

True

The multiplication 4 * 3 = 12 happens first, so a becomes 18. Since a is equal to b, the result of a >= b is True.

6. Less than or equal to (<=)

This operator checks if the value on the left is less than or equal to the value on the right.

Example:

a = 15 / 3
b = 6 + 2
result = a <= b
print(result)

Output:

True

Here, a becomes 5.0 (15 / 3), and b becomes 8 (6 + 2). Since 5.0 is less than 8, the result is True.

Key Points to Remember

  • Comparison operators have a lower operator precedence than arithmetic operators, which means they are evaluated after operations like addition, subtraction, and multiplication.

However, if you use parentheses, you can control the evaluation order.

Practice these examples and learn how to control program flow by making decisions based on values.

“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”

Examples of Precedence Of Logical Operators in Python

Logical operators in Python are used to combine conditional statements, allowing you to evaluate multiple conditions at once. These operators return True or False based on the conditions.

Here are the main logical operators in Python:

1. AND (and)

This operator returns True if both conditions are true.

Example:

x = 5
y = 10
result = (x > 3) and (y < 15)
print(result)

Output:

True

Both conditions (x > 3 and y < 15) are True, so the result is True.

2. OR (or)

This operator returns True if at least one condition is true.

Example:

x = 5
y = 20
result = (x > 10) or (y < 25)
print(result)

Output:

True

Since one condition (y < 25) is True, the result is True.

3. NOT (not)

This operator inverts the truth value of the condition. If the condition is True, it returns False and vice versa.

Example:

x = 5
result = not (x > 10)
print(result)

Output:

True

Since x > 10 is False, not inverts it to True.

Key Takeaways

  • AND returns True only if both conditions are true.
  • OR returns True if at least one condition is true.
  • NOT inverts the result of the condition.

Keep experimenting to strengthen your understanding!

Examples of Precedence Of Arithmetic Operators in Python

Arithmetic operators in Python are used to perform mathematical operations on numbers. These operators allow you to perform basic calculations like addition, subtraction, multiplication, and more.

Let’s look at precedence of arithmetic operators in Python:

1. Addition (+)

Adds two numbers together.

Example:

x = 10
y = 5
result = x + y
print(result)

Output:

15

Here, 10 + 5 gives 15.

2. Subtraction (-)

Subtracts the right-hand number from the left-hand number.

Example:

x = 20
y = 8
result = x - y
print(result)

Output:

12

Subtracting 8 from 20 results in 12.

3. Multiplication (*)

Multiplies two numbers together.

Example:

x = 7
y = 6
result = x * y
print(result)

Output:

42

Multiplying 7 by 6 gives 42.

4. Division (/)

Divides the left-hand number by the right-hand number, always returning a float.

Example:

x = 15
y = 4
result = x / y
print(result)

Output:

3.75

Dividing 15 by 4 gives 3.75 (float result).

5. Modulus (%)

Returns the remainder of the division.

Example:

x = 17
y = 5
result = x % y
print(result)

Output:

2

17 % 5 gives a remainder of 2.

6. Exponentiation (**)

Raises the left-hand number to the power of the right-hand number.

Example:

x = 3
y = 2
result = x ** y
print(result)

Output:

9

3 ** 2 equals 9 (3 raised to the power of 2).

7. Floor Division (//)

Divides the left-hand number by the right-hand number and returns the largest integer less than or equal to the result.

Example:

x = 17
y = 3
result = x // y
print(result)

Output:

5

17 // 3 gives 5, which is the floor division result.

Key Takeaways

  • Addition, Subtraction, and Multiplication are straightforward calculations.
  • Division always returns a float, while floor division returns the largest integer less than or equal to the result.
  • Modulus gives the remainder of the division.
  • Exponentiation raises a number to a power.

Experiment with more complex expressions to deepen your knowledge!

Examples of Precedence of Bitwise Operators in Python

Bitwise operators in Python are used to manipulate individual bits of integer values. These operators work on the binary representations of numbers, allowing you to perform operations at the bit level.

Here are the key bitwise operators in Python:

1. AND (&)

Performs a bitwise AND operation. It returns 1 if both bits are 1; otherwise, it returns 0.

Example:

x = 10  # 1010 in binary
y = 4   # 0100 in binary
result = x & y
print(result)

Output:

0

Here, 1010 & 0100 gives 0000 in binary, which is 0 in decimal.

2. OR (|)

Performs a bitwise OR operation. It returns 1 if at least one bit is 1, otherwise, it returns 0.

Example:

x = 10  # 1010 in binary
y = 4   # 0100 in binary
result = x | y
print(result)

Output:

14

Here, 1010 | 0100 gives 1110 in binary, which is 14 in decimal.

3. XOR (^)

Performs a bitwise XOR (exclusive OR) operation. It returns 1 if the bits are different, otherwise returns 0.

Example:

x = 10  # 1010 in binary
y = 4   # 0100 in binary
result = x ^ y
print(result)

Output:

14

Here, 1010 ^ 0100 gives 1110 in binary, which is 14 in decimal.

4. NOT (~)

Performs a bitwise NOT operation, which inverts the bits. It flips 1 to 0 and 0 to 1.

Example:

x = 10  # 1010 in binaryresult = ~xprint(result)

Output:

-11

The bitwise NOT of 10 (which is 1010 in binary) inverts all the bits, resulting in -11 due to the way negative numbers are represented in Python.

5. Left Shift (<<)

Shifts the bits of a number to the left by a specified number of positions, effectively multiplying the number by 2 for each position shifted.

Example:

x = 5   # 0101 in binaryresult = x << 1print(result)

Output:

10

Shifting 5 (which is 0101 in binary) one position to the left gives 1010, which is 10 in decimal.

6. Right Shift (>>)

Shifts the bits of a number to the right by a specified number of positions, effectively dividing the number by 2 for each position shifted.

Example:

x = 10  # 1010 in binary
result = x >> 1
print(result)

Output:

5

Shifting 10 (which is 1010 in binary) one position to the right gives 0101, which is 5 in decimal.

Key Takeaways

  • AND returns 1 only when both bits are 1.
  • OR returns 1 if at least one bit is 1.
  • XOR returns 1 if the bits are different.
  • NOT inverts the bits, flipping 1 to 0 and vice versa.
  • Left and Right Shift operations shift the bits left or right, multiplying or dividing by 2 for each shift.

Keep practicing with these operators to get comfortable with bitwise manipulation!

Also Read: Comprehensive Guide to Binary Code: Basics, Uses, and Practical Examples

Examples of Precedence of Assignment Operators in Python

Assignment operators in Python are used to assign values to variables. These operators not only assign values but also perform arithmetic or bitwise operations in a shorthand way.

Here are the main assignment operators in Python:

1. Simple Assignment (=)

The = operator is used to assign a value to a variable.

Example:

x = 10
print(x)

Output:

10

Here, 10 is assigned to the variable x.

2. Add and Assign (+=)

This operator adds the right operand to the left operand and assigns the result to the left operand.

Example:

x = 5
x += 3
print(x)

Output:

8

Here, 3 is added to x, and the result is assigned back to x, so x becomes 8.

3. Subtract and Assign (-=)

This operator subtracts the right operand from the left operand and assigns the result to the left operand.

Example:

x = 10
x -= 4
print(x)

Output:

6

Here, 4 is subtracted from x, and the result is assigned back to x, so x becomes 6.

4. Multiply and Assign (*=)

This operator multiplies the left operand by the right operand and assigns the result to the left operand.

Example:

x = 6
x *= 2
print(x)

Output:

12

Here, x is multiplied by 2, and the result is assigned back to x, so x becomes 12.

5. Divide and Assign (/=)

This operator divides the left operand by the right operand and assigns the result to the left operand.

Example:

x = 10
x /= 2
print(x)

Output:

5.0

Here, 10 is divided by 2, and the result (5.0, since division always returns a float) is assigned to x.

6. Modulus and Assign (%=)

This operator takes the modulus of the left operand by the right operand and assigns the result to the left operand.

Example:

x = 10
x %= 3
print(x)

Output:

1

Here, the modulus of 10 by 3 is 1, and the result is assigned to x.

7. Exponentiate and Assign (**=)

This operator raises the left operand to the power of the right operand and assigns the result to the left operand.

Example:

x = 2
x **= 3
print(x)

Output:

8

Here, x is raised to the power of 3, so x becomes 8.

8. Floor Divide and Assign (//=)

This operator performs floor division (divides and rounds down) on the left operand by the right operand and assigns the result to the left operand.

Example:

x = 15
x //= 4
print(x)

Output:

3

Here, 15 // 4 gives 3 because floor division rounds down to the nearest integer.

Key Takeaways

  • Assignment Operators combine the assignment operation with other arithmetic operations, allowing for shorthand code.
  • You can use *+=, -=, =, /=, and others to update the value of variables without repeating the variable name.

Experiment with these operators in different scenarios to simplify your code and improve efficiency!

MCQs: Precedence of Operators in Python

1. Which operator has the highest precedence in Python?

a) Assignment (=)

b) Logical AND (and)

c) Exponentiation (**)

d) Addition (+)

2. What is the result of 3 + 2 * 2 in Python?

a) 10

b) 7

c) 9

d) 12

3. In Python, which of the following has lower precedence than arithmetic operators?

a) Logical operators

b) Exponentiation

c) Unary minus

d) Multiplication

4. What does the following expression evaluate to: True or False and False?

a) True

b) False

c) Syntax Error

d) None

5. What is the result of 4 * 2 ** 2 in Python?

a) 64

b) 16

c) 8

d) 4

6. Which of the following expressions shows correct operator precedence in Python?

a) not a and b

b) a + b * c

c) a = b == c

d) All of the above

7. What is the associativity of the exponentiation operator ** in Python?

a) Left to Right

b) Right to Left

c) No associativity

d) Depends on usage

8. Which of these operators has the lowest precedence in Python?

a) or

b) and

c) not

d) ==

9. You are debugging this expression: 5 + 3 * 2 ** 2 - 1. What should be the first operation evaluated?

a) 3 * 2

b) 2 ** 2

c) 5 + 3

d) 5 + 3 * 2

10. A developer wants to override default precedence in a + b * c to perform addition first. Which is correct?

a) a + (b * c)

b) (a + b) * c

c) (a + b) * (c)

d) (a + b) + c

11. Given a = True, b = False, what is the result of not a or b and a?

a) False

b) True

c) Syntax Error

d) None of the above

Conclusion 

Mastering the precedence of operators in Python is a fundamental step toward writing clean, predictable, and bug-free code. This guide has provided you with a clear hierarchy, from parentheses down to logical operators, and explained how associativity acts as the tiebreaker. 

While memorizing the entire chart is helpful, the most important takeaway is to write code that is easy to read. When in doubt, use parentheses () to make your intentions explicit. This not only guarantees the correct order of operations but also makes your code more maintainable for you and other developers. 

How upGrad can help you?

With upGrad, you can access global standard education facilities right here in India. upGrad also offers free Data Science Courses that come with certificates, making them an excellent opportunity if you're interested in data science and machine learning.

By enrolling in upGrad's Python courses, you can benefit from the knowledge and expertise of some of the best educators from around the world. These instructors understand the diverse challenges that Python programmers face and can provide guidance to help you navigate them effectively.

So, reach out to an upGrad counselor today to learn more about how you can benefit from a Python course.

Here are some of the best data science and machine learning courses offered by upGrad, designed to meet your learning needs:

Similar Reads: Top Trending Blogs of Python

FAQ's

1. What is operator precedence in Python? 

Operator precedence in Python is the set of rules that determines the order in which different operations are performed in a complex expression. Just like in mathematics, where multiplication is done before addition, Python has a predefined hierarchy for its operators. This ensures that an expression like 5 + 2 * 3 is consistently evaluated as 11 (2 * 3 first) and not 21. Understanding these rules is fundamental to writing correct and predictable code. 

2. How does Python handle operator precedence? 

Python handles operator precedence in Python by following a well-defined hierarchy of rules, which is often summarized by an acronym like PEMDAS (Parentheses, Exponents, Multiplication/Division, Addition/Subtraction) for arithmetic operations. The interpreter parses the expression and evaluates the operators with higher precedence before moving to those with lower precedence. For example, in 10 - 4 / 2, the division (/) has higher precedence than subtraction (-), so it is calculated first, resulting in 10 - 2 = 8. 

3. What is operator associativity, and how does it relate to precedence? 

Operator associativity is the rule that determines the order of operations when multiple operators have the same precedence level. Most operators in Python are left-associative, meaning they are evaluated from left to right. For example, in 10 - 4 + 2, subtraction and addition have the same precedence, so the expression is evaluated as (10 - 4) + 2, which equals 8. The main exception is the exponentiation operator (**), which is right-associative. 

4. Can I change operator precedence in Python? 

No, you cannot change the built-in rules for operator precedence in Python, as they are a fixed part of the language's syntax. However, you can and should use parentheses () to override the default order of operations. Any expression enclosed in parentheses is evaluated first, regardless of the precedence of the operators inside it. This is the best way to ensure your code is both correct and easy for others to read. 

5. What happens if I don’t use parentheses in an expression? 

If you don't use parentheses, Python will strictly follow its default rules for operator precedence in Python. This can sometimes lead to unexpected or incorrect results if you are not completely familiar with the precedence hierarchy. For example, a beginner might expect 3 * 5 + 2 to be calculated based on some other order, but Python will always perform the multiplication first. Relying on the default order can make your code less readable, so it's always a good practice to use parentheses to make your intentions clear. 

6. Which operator has the highest precedence in Python? 

The operator with the highest precedence in Python is the parenthesis () for grouping expressions. Following that, the exponentiation operator (**) has the next highest precedence among mathematical operators. This means that in an expression like 2 * 3 ** 2, the exponentiation (3 ** 2) is performed first, resulting in 2 * 9 = 18. 

7. Do logical operators have higher precedence than arithmetic operators? 

No, logical operators (and, or, not) have a lower precedence than all arithmetic operators. This means that in a mixed expression like 5 + 2 > 3 and 10 * 2 == 20, all the arithmetic and comparison operations will be evaluated first before the logical and is considered. Understanding this order is crucial when writing complex conditional statements. 

8. What is the precedence of comparison operators in Python? 

Comparison operators (like ==, !=, >, <, >=, <=) have a lower precedence than all arithmetic operators but a higher precedence than logical operators. This allows you to write expressions like 5 + 3 < 10 without needing parentheses. Python will first calculate 5 + 3 to get 8, and then it will evaluate 8 < 10 to get True. 

9. How do bitwise operators work in terms of precedence? 

Bitwise operators (like & for AND, | for OR, ^ for XOR, << for left shift, and >> for right shift) have a lower precedence than arithmetic operators but a higher precedence than comparison operators. For example, in 10 + 5 & 12, the addition will be performed first. The correct understanding of the precedence of operators in Python, including bitwise ones, is essential for low-level programming tasks. 

10. Can I mix arithmetic and logical operators in an expression? 

Yes, you can mix them, and it's a common practice in conditional logic. However, you must be mindful of the operator precedence in Python. All arithmetic operations will be performed first, followed by comparison operations, and finally, the logical operations will be evaluated. For clarity and to avoid subtle bugs, it is highly recommended to use parentheses to group the different parts of your expression. 

11. What is the difference between and and or in Python? 

The and operator is a logical operator that returns True only if both the expressions on its left and right sides are true. The or operator, on the other hand, returns True if at least one of the expressions is true. The and operator has a higher precedence than the or operator, which is an important detail in the precedence of operators in Python. 

12. What is short-circuiting in the context of logical operators? 

Short-circuiting is an efficient behavior of the and and or operators. For an and expression, if the first operand evaluates to False, Python will not even evaluate the second operand, because the entire expression is guaranteed to be false. Similarly, for an or expression, if the first operand is True, the second operand is skipped. This is an important performance optimization and is also relied upon for writing concise conditional code. 

13. How does the not operator work in terms of precedence? 

The logical not operator has a higher precedence than and and or. This means that in an expression like not False and True, the not False part is evaluated first (to True), and then the expression becomes True and True, which results in True. Understanding this is a key part of mastering the precedence of operators in Python. 

14. What is the assignment operator's precedence? 

The assignment operator (=) has one of the lowest precedences in Python. This is intentional, as it allows you to perform a full calculation on the right side of the operator before the result is assigned to the variable on the left. For example, in x = 5 + 10 / 2, the entire right side is calculated first (10, then assigned to x), resulting in x being assigned the value 10.0. 

15. What is the Walrus Operator (:=) and what is its precedence? 

The "walrus operator" (:=), introduced in Python 3.8, is an assignment expression. It allows you to assign a value to a variable as part of a larger expression. It has a very low precedence, just above comma. This is useful for simplifying certain patterns, like in a while loop, for example: while (line := f.readline()):. 

16. Does the order of operations matter in Python? 

Yes, the order of operations is absolutely critical. A misunderstanding of operator precedence in Python is a common source of bugs for beginners. An expression evaluated in the wrong order can produce a completely different and incorrect result. This is why it is essential to either learn the precedence rules or, more practically, use parentheses to explicitly control the order of evaluation and make your code's intent clear. 

17. How do I check operator precedence in Python? 

The most reliable way to check the precise precedence of operators in Python is to refer to the official Python documentation, which has a comprehensive table listing all operators from highest to lowest precedence. For a quick reference, you can search for a "Python operator precedence table" online. 

18. Are there any operators with the same level of precedence? 

Yes. For example, the multiplication (*), division (/), floor division (//), and modulo (%) operators all have the same level of precedence. Similarly, addition (+) and subtraction (-) share the same level. When operators of the same precedence appear in an expression, their order of evaluation is determined by their associativity (which is left-to-right for these arithmetic operators). 

19. How can I learn more about the precedence of operators in Python? 

The best way to learn is through a combination of studying the rules and hands-on practice. Start with a structured program, like the Python programming courses offered by upGrad, which will provide a strong conceptual foundation. Then, experiment in an interactive Python shell by writing complex expressions both with and without parentheses to see how Python evaluates them. This practical experimentation is key to solidifying your understanding. 

20. What is the single most important best practice regarding operator precedence? 

The single most important best practice is: when in doubt, use parentheses. While it is useful to know the rules of operator precedence in Python, your primary goal should be to write code that is clear, readable, and unambiguous. Using parentheses, even when not strictly necessary, makes your intentions explicit and can prevent subtle bugs, making your code easier for both you and others to maintain.

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
Pavan Vadapalli

Author|900 articles published

Pavan Vadapalli is the Director of Engineering , bringing over 18 years of experience in software engineering, technology leadership, and startup innovation. Holding a B.Tech and an MBA from the India....

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

text

Foreign Nationals

Disclaimer

  1. The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

  2. The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not .