Computer Science Related Others Courses AvailableThe Best Codder.blogspot.com

Precedence of Python Operators

 

Precedence of Python Operators

An expression is a collection of numbers, variables, operations, and built-in or user-defined function calls. The Python interpreter can evaluate a valid expression

Code

  1. 2 - 7  

Output:

-5

The expression 2 - 7 is used as an example here. In an expression, we can add multiple operators. There is a principle of precedence in Python for evaluating these types of expressions. It directs the sequence in which certain tasks are completed.

Division, for instance, takes precedence over addition.

Code

  1. # Division has higher precedence than addition  
  2. 16 + 16 / 2  

Output:

24.0

However, we can reverse this sequence by employing parenthesis (), which takes precedence over division.

Code

  1. # Parentheses () holds higher precedence  
  2. (16 + 16) / 2  

Output:

16.0

The following table shows the precedence of Python operators. It's in reverse order (the upper operator holds higher precedence than the lower operator).

OperatorsMeaning
()Parentheses
**Exponent
+x, -x, ~xUnary plus, Unary minus, Bitwise NOT
*, /, //, %Multiplication, Division, Floor division, Modulus
+, -Addition, Subtraction
<<, >>Bitwise shift operators
&Bitwise AND
^Bitwise XOR
|Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not inComparisons, Identity, Membership operators
notLogical NOT
andLogical AND
orLogical OR

Consider the following examples:

Assume we're building an if...else block that only executes if the color is red or green and quantity is greater than or equal to 5.

Code

  1. # Precedence of and and or operators  
  2. colour = "red"  
  3.   
  4. quantity = 0  
  5.   
  6. if colour == "red" or colour == "green" and quantity >= 5:  
  7.     print("Your parcel is dispatched")  
  8. else:  
  9.     print("your parcel cannot be dispatched")  

Output:

Your parcel is dispatched

Even though quantity is 0, this program runs if block. Because and takes precedence over or does not produce the anticipated result.

Post a Comment

© Python . The Best Codder All rights reserved. Distributed by