Operators in Python [Part-1]

An Operator is simply a symbol that is used to perform different types of operations. There are following types of operators to perform different types of operations in Python:
(a) Arithmetic operators
(b) Assignment operators
(c) Comparison operators
(d) Logical operators
(e) Identity operators
(f) Membership operators
(g) Bitwise operators

Arithmetic operators: The following table shows the arithmetic operators to perform common mathematical operations. Assume two variable x and y, then:
Operator Name Description Example
+ Addition Add two operands x + y
- Subtraction Subtracts second operand from the first x - y
* Multiplication Multiplies both operands x * y
/ Division Divides numerator by de-numerator x / y
% Modulus Remainder of the division x % y
** Exponentiation First operand raised to the power of second x ** y
// Floor division Rounds the result down to the nearest whole number x // y


Example -

x=5
y=2
print("Addition is:",x+y)
print("Subtraction is:",x-y)
print("Multiplication is:",x*y)
print("Division is:",x/y)
print("Modulus is:",x%y)
print("Exponentiation is:",x**y) #5**2=5*5
print("Floor Division is:",x//y)

Output will be

Addition is: 7
Subtraction is: 3
Multiplication is: 10
Division is: 2.5
Modulus is: 1
Exponentiation is: 25
Floor Division is: 2


Assignment operators: The following table shows the assignment operators used in Python to assign values to variables.
Operator Example Equivalent to
= x = 5 x = 5
+= x += 5 x = x + 5
-= x -= 5 x = x - 5
*= x *= 5 x = x * 5
/= x /= 5 x = x / 5
%= x %= 5 x = x % 5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x = x & 5
|= x |= 5 x = x | 5
^= x ^= 5 x = x ^ 5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5

Example -
a=5
print("a is",a)
b=5
b+=1 #b=5+1
print("b is",b)
c=5
c-=2 #c=5-3
print("c is",c)
d=5
d*=3 #d=5*3
print("d is",d)
e=10
e/=2 #e=10/2
print("e is",e)
f=5
f%=2 #f=5%2
print("f is",f)
g=5
g//=3 #g=5//2
print("g is",g)
h=5
h**=2 #h=5**2
print("h is",h)
i=5
i&=3 #i=5&3
print("i is",i)
j=5
j|=2 #j=5|2
print("j is",j)
k=5
k^=3 #k=5^3
print("k is",k)
l=5
l>>=2 #l=5>>2
print("l is",l)
m=5
m<<=2 #m=5<<2
print("m is",m)

Output will be
a is 5
b is 6
c is 3
d is 15
e is 5.0
f is 1
g is 1
h is 25
i is 1
j is 7
k is 6
l is 1
m is 20


0 Comments