Mathematical Operations in Python
What do you think is the output of the following program? Press the run button to find out.
I know what's on your mind! In the previous lesson, we said that any text we want to print must be in double quotes. But numbers are not text! Numbers can be printed without using quotes as well.
So now, what do you think the output of the following program is?
It's that simple to perform all arithmetic operations and see the output.
Python can perform the four basic mathematical operations:
Operation | Symbol |
---|---|
Addition | + |
Subtraction | - |
Multiplication | * |
Division | / |
Let's do some calculations. Before you run the program below, do the calculations in your mind once and then press the run button.
The order of performing mathematical operations is from left to right. Using this simple rule, the result of the above calculation can be obtained. What do you think the result of the following mathematical operation is?
In this problem, if we perform the operations from left to right and proceed as in the previous problem, we arrive at an incorrect answer. The reason for this is that each mathematical operation has a specific priority. The priority of mathematical operators is as follows:
Priority | Operator | Symbol |
---|---|---|
First | Parentheses | () |
Second | Multiplication and Division | * and / |
Third | Addition and Subtraction | + and - |
It is recommended to run the code in your mind before executing it. This will help you understand how the computer performs operations.
See the calculation process here!
As we mentioned, the highest priority in performing calculations is held by the parentheses operator. Here, we have three parentheses operators. So first, we calculate their values and replace them in the parentheses. After that, we perform multiplication first and then subtraction:
1print((3 + 5) - (12 - 7) * (10 / 2)) 2print((8) - (12 - 7) * (10 / 2)) 3print((8) - (5) * (10 / 2)) 4print((8) - (5) * (5)) 5print(8 - 5 * 5) 6print(8 - 25) 7print(-17)
In this section, we became familiar with printing numbers and how to perform mathematical operations in Python. With what you've learned, you can write a simple calculator program that performs the 4 basic operations!