Professional Documents
Culture Documents
4.1 Basic Math Operators PDF
4.1 Basic Math Operators PDF
As we have learned how to work with numbers(integers and floats), we can start to learn mathematical operators by using
them.
► Addition (+):
Addition operator performs just as they do in mathematics.
In [1]: a = 2
b = 3
a + b
Out[1]: 5
In [2]: x = 1.6
y = 3.7
z = 6.5
x + y + z
Out[2]: 11.8
► Substraction (-) :
Calculates difference of x and y as in math.
In [3]: a = 7
b = 8
c = 11
a - b - c
Out[3]: -12
In [4]: a = 4
b = 7
a - b
Out[4]: -3
In [5]: x = 1.4
y = 4.7
x - y
Out[5]: -3.3000000000000003
► Multiplication (*):
Calculates multiplication of x and y.
In [6]: a = 3
b = 8
a * b
Out[6]: 24
In [7]: i = 1.14
j = 3.46
i * j
Out[7]: 3.9443999999999995
In [8]: a = 2
b = 3
c = 5
a * b * c
Out[8]: 30
In [9]: a = 6
b = 7.2
a * b
Out[9]: 43.2
► Division (/):
Calculates division of x by y.
In [10]: 4 / 2
Out[10]: 2.0
In [11]: 9 / 6
Out[11]: 1.5
In [12]: 22 / 9
Out[12]: 2.4444444444444446
In [13]: 4 // 2
Out[13]: 2
Out[14]: 3
In [15]: 22 // 7
Out[15]: 3
In [16]: 40 // 7
Out[16]: 5
► Modulo (%)
The % operator is the modulo, which returns the remainder rather than the quotient after division.
This is useful for finding even, odd numbers or numbers that are multiples of the same number.
Out[17]: 1
In [18]: 5 % 2
Out[18]: 1
Out[19]: 0
► Power (**)
This operator in Python is used to raise the number on the left to the power of the exponent of the right. That is, in the
expression 5 ** 3, 5 is being raised to the 3rd power. In mathematics, we often see this expression rendered as 5³, and
what is really going on is 5 is being multiplied by itself 3 times.
In Python, we would get the same result of 125 by running either expression 5 ** 3, or 5 * 5 * 5.
In [20]: #5 ^ 3
5 ** 3
Out[20]: 125
In [21]: 2 ** 8
Out[21]: 256
In [22]: 3 ** 4
Out[22]: 81
So, what if we want to square root of a number. how can we do that? The answer is simple, as you know from math
lessons, the square root of a number is equal to power of 1/2 (0.5) of that number.
Out[23]: 6.0
► Negation (-)
Sometimes, we need to change signs of our number. For example, let's say that we have positive numbers, and we want
to convert into them negative numbers or vice versa. In such situations, we can use this operator practically.
In [24]: num = 3
-num
Out[24]: -3
In [25]: x = -5
-x
Out[25]: 5
► Operator Precedence
In Python, as in mathematics, we need to keep in mind that operators will be evaluated in order of precedence.
2) Multiplication and Dividing are always done before Addition and Subtraction.
Important Tip: If you may get confused in some operations, in order to guarantee for your calculation's accuracy,
Priority Operation
1 Parentheses
2 Exponent
3 Multiplication
4 Division
5 Addition
6 Subtraction
In [26]: 2 + 3 * 4 / 5 - 20
Out[26]: -15.6
Out[27]: -15.6
In [ ]: