sec01 - Order of operations

The four arithmetic operations in Python follow the same order as you learned in math class. For example, you may have learned the following rules.

  1. [Principle] Calculate from left to right
  2. Perform multiplication and division before addition and subtraction
  3. Calculate the part enclosed in parentheses first
  4. The order of addition and multiplication can be changed
    1. 5 - 3” can be interpreted as “5 + (-3),” which is equivalent to “(-3) + 5,” or “-3 + 5.”
    2. 5 * -3” can be rewritten as “-3 * 5.”

The calculation order is the same in Python, so let's verify it.

Order of addition, subtraction, multiplication, and division

Let's try executing the following code.

result1 = 5 + 4 * 2
print(result1)

result2 = 5 / 4 * 2
print(result2)

First, let's explain “5 + 4 * 2.” This calculation contains addition and multiplication. In this case, multiplication takes precedence. Therefore, first calculate “4 * 2” (the result is “8”), then calculate “5 + 8.” The output result of the result1 variable is “13.”

Next, let's look at “5 / 4 * 2.” In expressions consisting only of multiplication and division, calculations are performed from left to right. Therefore, first calculate “5 / 4” (the result is “1.25”), then calculate “1.25 * 2.” The output result of the result2 variable is “2.5.”

Indicate priority

Python, like arithmetic and mathematics, prioritizes calculations enclosed in parentheses. Let's try executing the following code.

result3 = (5 + 4) * 2
print(result3)

result4 = 5 / (4 * 2)
print(result4)

The part “5 + 4” in the calculation formula “(5 + 4) * 2” in the first line is enclosed in parentheses. In this case, the calculation inside the parentheses is performed first. Therefore, first calculate “5 + 4” (the result is “9”), then perform “9 * 2”. The output result of the variable “result3” is “18”.

Next, let's look at the expression “5 / (4 * 2)”. The part “4 * 2” is enclosed in parentheses. Therefore, first calculate “4 * 2” (the result is “8”), then execute “5 / 8”. The output result of the variable “result4” is “0.625”.

Python operator precedence

The precedence of each operator in Python (including parentheses) is summarized in the official documentation.

[Python Official Documentation] 6. Expressions > 6.17. Operator precedence

The link provides a table summarizing the precedence of each operator, with the highest priority at the top of the table. Among the operators we have learned so far, parentheses have the highest priority. Following that, the order is “exponentiation” > “multiplication, division, floor division, remainder” > “addition and subtraction.”

If you are unsure about the order of operations in Python, refer to the official documentation for clarification.

おすすめの記事