Python – Operators

Operators

Operator is a symbol that performs certain operations.

Python provides the following set of operators

  • Arithmetic Operators
  • Relational Operators or Comparison Operators
  • Logical operators
  • Bitwise operators
  • Assignment operators
  • Special operators
  • Membership Operators
  • Identity Operators

Arithmetic Operators:

+ ==>Addition
- ==>Subtraction
* ==>Multiplication
/ ==>Division operator
% ==>Modular operator
// ==>Floor Division operator
** ==>Exponent operator or power operator like as pow(a,b) function
Ex: test.py:
a=10
b=2
print('a+b=',a+b)
print('a-b=',a-b)
print('ab=',ab)
print('a/b=',a/b)
print('a//b=',a//b)
print('a%b=',a%b)
print('a**b=',a**b)
Output:
Python test.py or py test.py
a+b= 12
a-b= 8
ab= 20 
a/b= 5.0 
a//b= 5 
a%b= 0 
a*b= 100

Note: / 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 at least one argument is float type then result is float type.

Note:

  • 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.

If we use * operator for str type then compulsory one argument should be int and other argument should be str type.

2*”seed”

“seed”*2

2.5*”seed” ==>TypeError: can’t multiply sequence by non-int of type ‘float’

“seed”*”seed”==>TypeError: can’t multiply sequence by non-int of type ‘str’

+ ==>String concatenation operator

* ==>String multiplication operator

Relational Operators (Comparison Operator):

OperatorDescriptionExample
==If the values of two operands are equal, then the condition becomes true.(a == b) is not true.
!=If values of two operands are not equal, then condition becomes true.(a != b) is true.
<>If values of two operands are not equal, then condition becomes true.(a <> b) is true. This is similar to != operator.
>If the value of left operand is greater than the value of right operand, then condition becomes true.(a > b) is not true.
<If the value of left operand is less than the value of right operand, then condition becomes true.(a < b) is true.
>=If the value of left operand is greater than or equal to the value of right operand, then condition becomes true.(a >= b) is not true.
<=If the value of left operand is less than or equal to the value of right operand, then condition becomes true.(a <= b) is true.
Ex 1:
a=10
b=20
print("a > b is ",a>b)
print("a >= b is ",a>=b)
print("a < b is ",a<b)
print("a <= b is ",a<=b)
a > b is False
a >= b is False
a < b is True
a <= b is True

We can apply relational operators for str types also

Ex 2:
a="seed"
b="seed"
print("a > b is ",a>b)
print("a >= b is ",a>=b)
print("a < b is ",a<b)
print("a <= b is ",a<=b)
a > b is False
a >= b is True
a < b is False
a <= b is True
Ex:
print(True>True) False
print(True>=True) True
print(10 >True) True
print(False > True) False
print(10>'seed')
TypeError: '>' not supported between instances of 'int' and 'str'

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
>>>”seed”==”seed”
True
>>> 10==”seed”
False

Note: Chaining concept is applicable for equality operators. If atleast one comparison returns False then the result is False. Otherwise the result is true.

Ex:
>>> 10==20==30==40
False
>>> 10==10==10==10
True

Logical Operators:

and, or ,not

We can apply for all types.

For boolean types behaviour:

and ==>If both arguments are True then only result is True
or ====>If at least one argument is True then result is True
not ==>complement

True and False ==>False
True or False ===>True
not False ==>True

For non-boolean types behaviour:
0 means False
non-zero means True
empty string is always treated as False

x and y:
==>if x is evaluates to false return x otherwise return y
Ex:
10 and 20
0 and 20

If first argument is zero then result is zero otherwise result is y

x or y:
If x evaluates to True then result is x otherwise result is y
10 or 20 ==> 10
0 or 20 ==> 20

not x:
If x is evalutates to False then result is True otherwise False
not 10 ==>False
not 0 ==>True

Ex:
"seed" and "dharshi" ==>dharshi
"" and "seed" ==>""
"seed" and "" ==>""
"" or "seed" ==>"seed"
"seed" or ""==>"seed"
not ""==>True
not "seed" ==>False

Bitwise Operators:

  • We can apply these operators bitwise.
  • These operators are applicable only for int and boolean types.
  • By mistake if we are trying to apply for any other type then we will get Error.
OperatorDescriptionExample
& Binary ANDOperator copies a bit to the result if it exists in both operands(a & b) (means 0000 1100)
| Binary ORIt copies a bit if it exists in either operand.(a | b) = 61 (means 0011 1101)
^ Binary XORIt copies the bit if it is set in one operand but not both.(a ^ b) = 49 (means 0011 0001)
~ Binary Ones ComplementIt is unary and has the effect of ‘flipping’ bits.(~a ) = -61 (means 1100 0011 in 2’s complement form due to a signed binary number.
<< Binary Left ShiftThe left operands value is moved left by the number of bits specified by the right operand.a << 2 = 240 (means 1111 0000)
>> Binary Right ShiftThe left operands value is moved right by the number of bits specified by the right operand.a >> 2 = 15 (means 0000 1111)

print(4&5) ==>valid
print(10.5 & 5.6) ==>
TypeError: unsupported operand type(s) for &: ‘float’ and ‘float’
print(True & True) ==>valid

& ==> If both bits are 1 then only result is 1 otherwise result is 0
| ==> If atleast one bit is 1 then result is 1 otherwise result is 0
^ ==>If bits are different then only result is 1 otherwise result is 0
~ ==>bitwise complement operator
1 ==>0 & 0==>1
<< ==>Bitwise Left shift
>> ==> Bitwise Right Shift

print(4&5) ==>4
print(4|5) ==>5
print(4^5) ==>1

We can apply bitwise operators for boolean types also
print(True & False) ==>False
print(True | False) ===>True
print(True ^ False) ==>True
print(~True) ==>-2
print(True<<2) ==>4
print(True>>2) ==>0

Assignment Operators:

We can use assignment operator to assign value to the variable.
Ex:
x=10

We can combine assignment operator with some other operator to form compound assignment operator.
Ex: x+=10 ====> x = x+10

The following is the list of all possible compound assignment operators in Python
+=
-=
*=
/=
%=
//=
**=
&=
|=
^=
>>=
<<=

Ex:
x=10
x+=20
print(x) ==>30

Ex:
x=10
x&=5
print(x) ==>0

Ternary Operator:

Syntax:
x = first Value if condition else second Value

If condition is True then first Value will be considered else second Value will be considered.

Ex 1:
a,b=10,20
x=30 if a<b else 40
print(x) #30

Ex 2: Read two numbers from the keyboard and print minimum value
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
min=a if a<b else b
print("Minimum Value:",min)

Output:
Enter First Number:10
Enter Second Number:30
Minimum Value: 10

Note: Nesting of ternary operator is possible.

Q. Program for minimum of 3 numbers
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
c=int(input("Enter Third Number:"))
min=a if a<b and a<c else b if b<c else c
print("Minimum Value:",min)

Ex:
a=int(input(“Enter First Number:”))
b=int(input(“Enter Second Number:”))
print(“Both numbers are equal” if a==b else “First Number is Less than Second Number” if a<b else “First Number Greater than Second Number”)

Output:
D:\python_classes>py test.py
Enter First Number:10
Enter Second Number:10
Both numbers are equal

D:\python_classes>py test.py
Enter First Number:10
Enter Second Number:20
First Number is Less than Second Number

D:\python_classes>py test.py
Enter First Number:20
Enter Second Number:10
First Number Greater than Second Number

Special operators:

Python defines the following 2 special operators

  • Identity Operators
  • Membership operators

Identity Operators

We can use identity operators for address comparison.
2 identity operators are available

is
is not

r1 is r2 returns True if both r1 and r2 are pointing to the same object
r1 is not r2 returns True if both r1 and r2 are not pointing to the same object

Ex:
a=10
b=10

print(a is b) True
x=True
y=True

print( x is y) True

Ex:
a=”seed”
b=”seed”
print(id(a))
print(id(b))
print(a is b)

Ex:
list1=[“one”,”two”,”three”]
list2=[“one”,”two”,”three”]
print(id(list1))
print(id(list2))
print(list1 is list2) False
print(list1 is not list2) True

print(list1 == list2) True

Note:
We can use is operator for address comparison whereas == operator for content comparison.

Membership operators:

We can use Membership operators to check whether the given object present in the given collection.(It may be String,List,Set,Tuple or Dict)

in => Returns True if the given object present in the specified Collection
not in =>Retruns True if the given object not present in the specified Collection

Ex:
x=”hello learning Python is very easy!!!”
print(‘h’ in x) True
print(‘d’ in x) False
print(‘d’ not in x) True
print(‘Python’ in x) True

Ex:
list1=[“seed”,”dharshi”,”technologies”,”shishir”]
print(“seed” in list1) True
print(“india” in list1) False
print(“delhi” not in list1) True

Python Operators Precedence

Sr.No.Operator & Description
1**Exponentiation (raise to the power)
2~ + –Complement, unary plus and minus (method names for the last two are +@ and -@)
3* / % //Multiply, divide, modulo and floor division
4+ –Addition and subtraction
5>> <<Right and left bitwise shift
6&Bitwise ‘AND’
7^ |Bitwise exclusive `OR’ and regular `OR’
8<= < > >=Comparison operators
9<> == !=Equality operators
10= %= /= //= -= += *= **=Assignment operators
11is is notIdentity operators
12in not inMembership operators
13not or andLogical operators
Follow Us On