For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
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.
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.
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.
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:
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]
The Associativity Rule in Python determines the order in which operators of the same precedence level are evaluated.
There are two types of associativity:
These concepts will help you write more accurate and reliable code.
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:
This operator checks if two values are equal.
Example:
x = 5 + 2
y = 3 * 2 + 1
result = x == y
print(result)
Output:
True
Here, x becomes 7 (5 + 2), and y also evaluates to 7 (3 * 2 + 1), so x == y returns True.
This operator checks if two values are not equal.
Example:
a = 10 - 3
b = 5 * 2
result = a != b
print(result)
Output:
False
Here, a is 7 (10 - 3), and b is also 10 (5 * 2), so a != b evaluates to False.
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.
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.
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.
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
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!”
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:
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.
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.
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
Keep experimenting to strengthen your understanding!
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:
Adds two numbers together.
Example:
x = 10
y = 5
result = x + y
print(result)
Output:
15
Here, 10 + 5 gives 15.
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.
Multiplies two numbers together.
Example:
x = 7
y = 6
result = x * y
print(result)
Output:
42
Multiplying 7 by 6 gives 42.
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).
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.
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).
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
Experiment with more complex expressions to deepen your knowledge!
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:
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.
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.
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.
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.
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.
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
Keep practicing with these operators to get comfortable with bitwise manipulation!
Also Read: Comprehensive Guide to Binary Code: Basics, Uses, and Practical Examples
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:
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.
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.
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.
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.
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.
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.
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.
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
Experiment with these operators in different scenarios to simplify your code and improve efficiency!
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
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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()):.
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.
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.
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).
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.
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.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author|900 articles published
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
Foreign Nationals
The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not .
Recommended Programs