Precedence of Python Operators
This is used in an expression with more than one operator with different precedence to determine which operation to perform first.
Example
10 + 20 * 30
10 + 20 * 30 is calculated as 10 + (20 * 30)
and not as (10 + 20) * 30
Python Code of the above Example
Python3
# Precedence of '+' & '*' expr = 10 + 20 * 30 print (expr) |
Output
610
Precedence of Logical Operators in Python
In the given code, the ‘if‘ block is executed even if the age is 0. Because the precedence of logical ‘and‘ is greater than the logical ‘or‘.
Python3
# Precedence of 'or' & 'and' name = "Alex" age = 0 if name = = "Alex" or name = = "John" and age > = 2 : print ( "Hello! Welcome." ) else : print ( "Good Bye!!" ) |
Output
Hello! Welcome.
Hence, To run the ‘else‘ block we can use parenthesis( ) as their precedence is highest among all the operators.
Python3
# Precedence of 'or' & 'and' name = "Alex" age = 0 if (name = = "Alex" or name = = "John" ) and age > = 2 : print ( "Hello! Welcome." ) else : print ( "Good Bye!!" ) |
Output
Good Bye!!
Precedence and Associativity of Operators in Python
In Python, operators have different levels of precedence, which determine the order in which they are evaluated. When multiple operators are present in an expression, the ones with higher precedence are evaluated first. In the case of operators with the same precedence, their associativity comes into play, determining the order of evaluation.