Basic Arithmetic Precedence
In Python, as in standard mathematics, some arithmetic operators have a higher precedence than others. Specifically, multiplication (*) and division (/) are performed before addition (+) and subtraction (-). When operators have the same precedence, they are evaluated from left to right.
Let's observe this behavior. The setup process has already created a file for you. In the WebIDE file explorer on the left, find and open the file named operator_precedence.py located in the ~/project directory.
Add the following code to the file:
## Multiplication and division are evaluated before addition and subtraction.
result = 10 + 4 * 3 - 10 / 5
print(result)
This expression contains addition, multiplication, subtraction, and division. Let's predict the order of operations:
- Python will first perform the multiplication:
4 * 3 equals 12.
- Next, it will perform the division:
10 / 5 equals 2.0. Note that standard division in Python 3 always results in a floating-point number.
- The expression is now
10 + 12 - 2.0.
- Finally, it will perform the addition and subtraction from left to right:
10 + 12 is 22, and 22 - 2.0 is 20.0.
Save the file by pressing Ctrl + S. To run the code, open a terminal in the WebIDE (Terminal -> New Terminal) and execute the following command:
python ~/project/operator_precedence.py
You will see the calculated result printed to the terminal.
20.0
The output matches our prediction, confirming the precedence of multiplication and division over addition and subtraction.