In the previous segment, you learned about various data types in Python. Arithmetic operations are an integral part of every programming language. Let's understand how you perform one in Python from the following video.
To do some mathematical operation which involves one or more than one operators, we did follow some rules. Same is the case in Python where if multiple operations have to be done in a single problem, then we make use of operator precedence rule.
Let us understand Operator precedence using an example.
a = 4+(8**2)-3**2%1
To find the value of the variable 'a', the following steps have to be followed.
Step 1: The first step is to deal with brackets as it holds the highest precedence among all operators in the given expression. The expression inside these brackets [(8**2)] will get executed first to return 64.
Updated Expression: 4+64-3**2%1
Step 2: Moving on, you deal with the exponentiation operator [3**2] as it has the next highest precedence when compared to other operators in the expression.
Updated Expression: 4+64-9%1
Step 3: Now you deal with the remainder operator as it has higher precedence over subtraction and addition. This means the value 9%1 gets evaluated to return 0.
Updated Expression: 4+64-0
Step 4: In the next step, the addition operator gets executed as it holds higher precedence over subtraction.
Updated Expression: 68−0
Step 5: The final step would be to perform subtraction
Answer: 68
And this is how operator precedence rule plays an important part while doing arithmetic operations in Python.