How to perform a mathematical operation on python variables?
In python you can perform arithmetic like addition, subtraction, multiplication, division, exponential, modulus, floor division on variables. To understand better please see below:
Addition (+): Adds value at either side of the value
#Declaring a variable
a = 20
b = 30
#Addition
c = a+b
print(c)
Subtraction (-): Subtract value right hand value from left hand
#Declaring a variable
a = 20
b = 30
#Subtraction
c = a-b
print(c)
Multiplication (*): Multiply value at either side
#Declaring a variable
a = 20
b = 30
#Multiplication
c = a*b
print(c)
Division (/): Divide left side value by right side and return the quotient.
#Declaring a variable
a = 20
b = 30
#Division
c = a/b
print(c)
Modulus (%): This operation also divides the left side value by right side value, but it returns the remainder, run below code and see the difference between division and modulus.
#Declaring a variable
a = 20
b = 30
#Modulus
c = a%b
print(c)
Exponential (**): If you want to calculate exponential of any value then this operator will help in python. Run below code and see how it works.
#Declaring a variable
a = 20
b = 30
#Exponential
c = a**b
print(c)
Floor Division (//): This operator divides the left side value by the right side and returns the quotient but removes the digits after the decimal point. But in case of any negative operand, the results will be floored, rounded away from zero to infinity (towards negative). Run below piece of code for better understanding:
#Declaring a variable
a = 20
b = 70
#Exponential
c = b//a
print(c)
For negative operand run below code and see the difference in result in both code:
#Declaring a variable
a = 20
b = -70
#Exponential
c = b//a
print(c)