Tuesday, November 5, 2019

PRECEDENCE AND ASSOCIATIVITY IN PYTHON

Precedence of Python Operators:

The combination of values, variablesoperators and function calls is termed as an expression. A Python interpreter can evaluate a valid expression.
For example:
  1. >>> 5 - 7
  2. -2
Here 5 - 7 is an expression. There can be more than one operator in an expression.
To evaluate these type of expressions there is a rule of precedence in Python. It guides the order in which operators are carried out.
For example, multiplication has a higher precedence than subtraction.
# Multiplication has higher precedence
# than subtraction
# Output: 2
10 - 4 * 2
But we can change this order using parentheses () as it has higher precedence.
# Parentheses () has higher precedence
# Output: 12
(10 - 4) * 2

The operator precedence in Python is listed in the following table. It is in descending order, the upper group has higher precedence than the lower ones.
Operator precedence rule in Python:
Operators-Meaning
()-Parentheses
**-Exponent
+x, -x, ~x-Unary 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 in-Comparisions, Identity, Membership operators
not-Logical NOT
and-Logical AND
or-


Associativity of Python Operators    :     

We can see in the above table that more than one operator exists in the same group. These operators have the same precedence.
When two operators have the same precedence, associativity helps to determine the order of operations.
Associativity is the order in which an expression is evaluated that has multiple operators of the same precedence. Almost all the operators have left-to-right associativity.
For example, multiplication and floor division have the same precedence. Hence, if both of them are present in an expression, the left one is evaluates first.

    # Left-right associativity
    # Output: 3
    print(5 * 2 // 3)

    # Shows left-right associativity
    # Output: 0
    print(5 * (2 // 3))

Logical OR

No comments:

Post a Comment

if you have any doubt please let me know.

LOOPS IN PYTHON.

ITERATION/LOOPING. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. Repe...

recent one