Python 3 – Operators Precedence Example
In programming, the order of operations is crucial in ensuring that the computation is done accordingly. Python 3 has a set of precedence rules in determining the sequence of evaluating the expressions. The operators of lower precedence are evaluated first before the higher precedence operators. This helps in reducing confusion as it ensures that the code executes in the intended order.
Here are the different operators precedence in Python 3:
**
(Exponentiation)~ + -
(Bitwise NOT, Unary Plus and Minus)* / % //
(Multiplication, Division, Modulus and Floor Division)+ -
(Addition and Subtraction)>> <<
(Right and Left bitwise shift)&
(Bitwise AND)^ |
(Bitwise XOR and OR)<= < > >=
(Comparison Operators)<> == !=
(Equality Operators)= %= /= //= -= += *= **=
(Assignment Operators)is is not
(Identity Operators)in not in
(Membership Operators)not or and
(Logical Operators)
Examples of Python 3 Operators Precedence
Example 1: Exponentiation
In this example, the operator ** has the highest precedence in Python 3. It means that this operator is evaluated first.
a = 2
b = 3
c = 4
result = a + b ** c
print(result)
Output:
64
The result of this code is 64 because the exponentiation operator, ** is evaluated first before the addition operator, +. Thus, the value of b is raised to the power of c (3^4), and the result is added to a (2). Therefore, the final answer is 2 + 3^4 = 64.
Example 2: Multiplication and Division
In this example, the multiplication and division operators have a higher precedence over the addition and subtraction operators.
a = 20
b = 10
c = 4
result = a + b * c / 2
print(result)
Output:
40
The result of this code is 40. Multiplication and division have a higher precedence than addition and subtraction, so b is multiplied by c then divided by 2. After that, the result is added to a. Therefore, the final answer is 20 + 10 * 4 / 2 = 40.
Example 3: Assignment Operators
In this example, we will look at the assignment operators.
a = 5
a += 2
print(a)
Output:
7
The answer is 7 because the value of a is increased by 2 using the shorthand operator, +=.
Example 4: Logical Operators
In this example, we will look at the logical operators.
a = 10
b = 20
c = 5
result = (a > b) or (c < b)
print(result)
Output:
True
The answer is True because one of the conditions in the logical operator, or, is true. This means that if either the first condition (a > b) or the second condition (c < b) is true, then the overall result is true.
Conclusion
A good understanding of operators precedence is essential in programming as it simplifies the coding process and greatly reduces the probability of errors. In Python 3, the sequence of evaluating expressions is determined by the rules of precedence. It is essential to follow these rules to ensure that the code executes as intended. In summary, knowing the operators precedence makes it easier to write more readable and efficient code.