5 Python Operators
5 Python Operators
Unary Operators
Binary Operators
Arithmetic Operators
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Example
• a=10
• b=2
• print('a+b=',a+b) • a+b= 12
• print('a-b=',a-b) • a-b= 8
• print('a*b=',a*b) • a*b= 20
• print('a/b=',a/b) • a/b= 5.0
• print('a//b=',a//b) • a//b= 5
• print('a%b=',a%b) • a%b= 0
• print('a**b=',a**b) • a**b= 100
Example
• a=10.5
• b=2
• print('a+b=',a+b) • a+b= 12.5
• print('a-b=',a-b) • a-b= 8.5
• print('a*b=',a*b) • a*b= 21.0
• print('a/b=',a/b) • a/b= 5.25
• print('a//b=',a//b) • a//b= 5.0
• print('a%b=',a%b) • a%b= 0.5
• print('a**b=',a**b) • a**b= 110.25
• / operator always performs floating point
arithmetic. Hence it will always returns float
value.
• But Floor division (//) can perform both floating
point and integral arithmetic.
• If arguments are int type then result is int type. If
atleast one argument is float type then result is
float type.
• 10/2==>5.0
• 10//2==>5
• 10.0/2===>5.0
• 10.0//2===>5.0
• We can use +,* operators for str type also.
• If we want to use + operator for str type then
compulsory both arguments should be str
• type only otherwise we will get error.
• >>> “GPREC“ + 10
• TypeError: must be str, not int
• >>> “GPREC“ + "10"
• ‘GPREC10‘
• a=“GPREC"
• b=“GPREC"
• print("a > b is ",a>b) • a > b is False
• print("a >= b is ",a>=b) • a >= b is True
• print("a < b is ",a<b) • a < b is False
• print("a <= b is ",a<=b) • a <= b is True
Chaining of operators
• Chaining of relational operators is possible.
• In the chaining, if all comparisons returns True
then only result is True.
• If atleast one comparison returns False then the
result is False
• 10<20 ==>True
• 10<20<30 ==>True
• 10<20<30<40 ==>True
• 10<20<30<40>50 ==>False
Equality operators (== , !=)
• We can apply these operators for any type even for incompatible
types also
>>> 10==20 False
>>> 10!= 20 True
>>> 10==True False
>>> False==False True
>>> “gprec"==“gprec“ True
>>> 10==“gprec“ False
<< Zero fill Shift left by pushing zeros in from the x << 2
left shift right and let the leftmost bits fall off
list1=["sunny","bunny","chinny","pinny"]
print("sunny" in list1) True
print("tunny" in list1) False
print("tunny" not in list1) True
OPERATOR PRECEDENCE AND ASSOCIATIVITY
OPERATOR PRECEDENCE AND ASSOCIATIVITY