Understanding Operator Precedence in Python

Updated on September 2, 2024

Article Outline

In Python, the operator precedence determines the order in which operators are evaluated in an expression. Ensuring that your source code performs the intended calculations is crucial. Misunderstanding the operator precedence can lead to subtle bugs and unexpected behaviour in your programs. This article explained everything about the operator Precedence in Python and its examples.

Operators Precedence in Python

The Operator’s precedence in Python determines the order in which different operators in an expression are evaluated. Operators with higher precedence are evaluated before those with lower precedence. This hierarchy of precedence ensures that expressions are evaluated consistently.

 

The following program demonstrates the Python Operator Precedence:

 

Program

def demonstrate_precedence(): arithmetic_result = 2 + 3 * 4 print(f"Example 1: 2 + 3 * 4 = {arithmetic_result}")   exponentiation_result = 2 ** 3 * 4 print(f"Example 2: 2 ** 3 * 4 = {exponentiation_result}")   parentheses_result = (2 + 3) * 4 print(f"Example 3: (2 + 3) * 4 = {parentheses_result}")   unary_result = -2 ** 3 print(f"Example 4: -2 ** 3 = {unary_result}")   logical_result = True or False and False print(f"Example 5: True or False and False = {logical_result}")   comparison_result = 5 < 10 == 10 print(f"Example 6: 5 < 10 == 10 = {comparison_result}")   bitwise_result = 4 & 3 | 2 print(f"Example 7: 4 & 3 | 2 = {bitwise_result}")   x = 5 conditional_result = x if x > 0 else -x print(f"Example 8: x if x > 0 else -x = {conditional_result}")   if __name__ == "__main__": demonstrate_precedence()

Output 

Example 1: 2 + 3 * 4 = 14 Example 2: 2 ** 3 * 4 = 32 Example 3: (2 + 3) * 4 = 20 Example 4: -2 ** 3 = -8 Example 5: True or False and False = True Example 6: 5 < 10 == 10 = True Example 7: 4 & 3 | 2 = 2 Example 8: x if x > 0 else -x = 5
*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Python Operators Precedence Table

The following table describes the Operator’s Precedence:

 

Operators Description
() Parentheses for grouping
‘**” Exponentiation (right associative)
‘+x’, ‘-x’ , ‘~x’ Unary plus, unary minus, bitwise NOT
‘*’ , ‘/’, ‘%’, ‘//’ Multiplication, division, modulo, floor division
‘+’, ‘-’ Addition, Subtraction
‘<<’, “>>” Bitwise left shift, bitwise right shift
‘&’ Bitwise AND
‘^’ Bitwise XOR
‘==”, ‘!=’ ,’ >’ ‘<’ , ‘>=’ , ‘<=’ Equality, inequality, comparison
‘not’ Logical Not
‘or’ Logical OR
‘if-else’  Conditional expression (ternary operator)
‘=’, ‘+=’, ‘-=’ , ‘*=’ , ‘/=’, etc Assignment operators and augmented assignments
‘,’ The comma (used for tuple packing and function arguments)
‘:’ It is used in slices, annotations, and dictionary key-value pairs

Python Operators Precedence Rule – PEMDAS

Python operator precedence follows the PEMDAS rule for arithmetic expression.  The precedence of operators is listed below in a high-to-low manner.

 

  • P – Parentheses
  • E – Exponentiation
  • M – Multiplication
  • D – Division
  • A – Addition
  • S – Subtraction

Associativity Rule

 

In Python, All the operators follow the left-to-right pattern except the exponentiation (**) operator. In other words, the evaluation will proceed from left to right.

 

For  Example : (99 + 55 – 9 /3 * 5)

 

In this example, the multiplication and division operators have equal precedence. However, they are evaluated according to the left-to-right associativity.

 

The following program demonstrates the Associativity Rule :

 

Program 

a = (24 ** 2 // 5 % 34 / 30 * 8) b = (9 << 10 >> 5) c = (3 ** 2 ** 2) print (a) print (b) print (c) <strong>Output</strong> 3.466666666666667 288 81

Comparison Operators

All the comparison operations in Python, such as <,>,==,  >=, <=, != have the same priority. The lower arithmetic, shifting and bitwise operations. Unlike in C, Python always follows the conventional mathematical interpretation for expressions like a < b < c.

 

The following program demonstrates the comparison Operation in Java:

 

Program

a = 10 b = 20   print("{a} > {b}: {a > b}") print("{a} < {b}: {a < b}") print("{a} == {b}: {a == b}") print("{a} != {b}: {a != b}") print("{a} >= {b}: {a >= b}") print("{a} <= {b}: {a <= b}")   x = "Harry" y = "Potter"   print('"{x}" > "{y}": {x > y}') print('"{x}" < "{y}": {x < y}')<strong> </strong>

Output 

{a} > {b}: {a > b} {a} < {b}: {a < b} {a} == {b}: {a == b} {a} != {b}: {a != b} {a} >= {b}: {a >= b} {a} <= {b}: {a <= b} "{x}" > "{y}": {x > y} "{x}" < "{y}": {x < y}

Examples of Comparison Operators

In this section, we will see some operator precedence in Python to get a good idea of how these things work internally.

Precedence of Operators

The following program demonstrates the Precedence of Operators:

 

Program

a = (105+ 12 * 35% 30 / 2) b = (3 ^ 2 << 9 + 48 // 24) print (a) print (b)

Output 

105.0 4099

Conclusion

In Python, operator precedence refers to the order in which Python evaluates or performs operators in an expression. It defines how more than one operator is applied within proximity. Keeping things clear and accurate in the code is always better from right to left.

 

To be certain of the clarity and correctness of source code, parentheses should be used explicitly to define the intended order of operations in all situations where there might be a mixing of operators with different precedence levels.

 

We know the rules of precedence and apply them by writing expressions evaluated as intended, which may then be used to maintain readable and reliable source code.

FAQs
Operator precedence refers to the rules determining how different operators are evaluated in an expression. Operators with higher precedence are executed before those with lower precedence.
The associativity determines the order in which operations of the same precedence level are evaluated. Most operators in Python are left-associative, meaning they are evaluated from left to right. However, exponentiation (‘**’) is right-associative and is evaluated from right to left.
The comparison operators in Python (eg ‘==’, ‘!=’ ‘<’, ‘>’, ‘<=’, ‘>=’)  have lower precedence than arithmetic operators. They are evaluated after arithmetic operations and before logical operators.
The ‘is’ and ‘is not’ operators, used for identity comparisons, have the same precedence level as comparison operators. They are evaluated after arithmetic operators and before logical operations.
The ‘del’ keyword has a lower precedence than most other operators. For example, in ‘del a[1+2]’, the addition is evaluated first before the deletion.

Updated on September 2, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved