Python Operator Precedence

Python operators have a set order of precedence, which determines what operators are evaluated first in a potentially ambiguous expression. For instance, in the expression 3 * 2 + 7, first 3 is multiplied by 2, and then the result is added to 7, yielding 13. The expression is not evaluated the other way around, because * has a higher precedence than +. Learn More about Python Operator Precedence

Below is a list of operators by precedence, and a brief description of what they (usually) do.

Simple Operator Precedence Examples in python

Python follows PEMDAS rule. PEMDAS stands for Parentheses, Exponents, Multiplication and Division, and Addition and Subtraction.

Example:

a, b, c, d = 2, 3, 5, 7
a ** (b + c) # parentheses
256
a * b ** c # exponent: same as a * (b ** c)
7776
a + b * c / d # multiplication / division: same as a + (b * c / d) 4.142857142857142
Extras: mathematical rules hold, but not always:
300 / 300 * 200
200.0
300 * 200 / 300
200.0
1e300 / 1e300 * 1e200
1e+200
1e300 * 1e200 / 1e300
inf

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 evaluated first.

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

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

Output

3
0

Specification

  • The input expression will not contain parenthesis and every operator is left-associative.
  • The input expression will only contain nonnegative integers. However, subexpressions may evaluate to negatives (e.g. 1 – 4).
  • You can take the expression in any reasonable format. For example:
    • “9 * 8 + 1 – 4”
    • “9*8+1-4”
    • [9, “*”, 8, “+”, 1, “-“, 4]
    • [9, 8, 1, 4], [“*”, “+”, “-“]
  • The input will contain at least 1 and at most 10 operators.
  • Any expression that contains a division or modulo by 0 should be ignored.
  • You can assume that modulo will not be given negative operands.

Test Cases

9 * 8 + 1 - 4 32 1 + 3 * 4 3 1 + 1 0 8 - 6 + 1 * 0 8 60 / 8 % 8 * 6 % 4 * 5 63

Learn More Here

LEAVE A REPLY

Please enter your comment!
Please enter your name here