It has been clear to you that there are two types of numbers in programming. i.e. integers and floating-point numbers.
The arithmetic operations in Python are the same as everyday math and they revolve around these two data types.
There are seven basic types of arithmetic operators. These are:
Addition (+) : Adds two numbers. e.g.
print(10 + 4)
Subtraction (-): Subtract the second number from the first. e.g.
print(10 - 4)
Multiplication (*): Multiply two numbers. e.g.
print(10 * 4)
Division (/): Performs division on two numbers. e.g.
print(10 / 4)
Floor Division (//): Performs division and rounds off the answer to the nearest integer. e.g.
print(10 // 4)
Modulo Operator (%): Performs division and returns the remainder. e.g.
print(10 % 4)
Exponent (**): Takes the power of the integer e.g.
print(10 ** 4)
All of these operations are shown below:
Now for all these operators that you learned, we have an augmented assignment operator. Let me show you how it is used.
Let’s say we have a variable called ‘x’. We set it to 10, now we want to increment this by 3, we’ll have to write code like this.
x = 10
x = x + 3
Python interpreter will add 3 in ‘x’ and store it in ‘x’. Let’s print this:
An augmented assignment operator can be used to replicate the same functionality but more efficiently.
The same code will be written like this.
x = 10
x += 3
Now, this operator can be used for subtraction and multiplication too. Look at this program.
Here we are first incrementing ‘x’ by 3 and then multiplying it by 3. The output of line 2 should be 13 and the output of line 3 should be 39.
In math, we have a concept called operator precedence, which means the order of execution of operations in an equation. It’s not specific to Python, and all programming languages follow the operator precedence. Let me remind you of the order:
- Division or Multiplication
- Addition or Subtraction
Let’s write a program and check this:
x = 10 + 3 * 2 ** 2 - (9 + 2)
What should be the answer to the above equation?
If your answer is 11, you don’t need to repeat high school.