Python Operators

Operators are special symbols in python that carry out arthimetic and logical operations.

Example


In [1]:
2 + 3


Out[1]:
5

'+ is the operator symbol, 2 and 3 are the operands

Operator Types

  1. Arithmetic Operators
  2. Comparison Operators
  3. Logical Operators
  4. Bitwise Operators
  5. Assignment Operators
  6. Special Operators

Arithmetic Operators


In [7]:
x = 15
y = 6

# Addition Operator
print('x + y = ', x + y)

# Subtraction Operator
print('x - y = ', x - y)

# Multiplication Operator
print('x * y = ', x * y)

# Division Operator
print('x / y = ', x / y) # True Division
print('x // y =', x//y) # Class Division

# Exponential Operator
print('x ** y = ', x ** y)


x + y =  21
x - y =  9
x * y =  90
x / y =  2.5
x // y = 2
x ** y =  11390625

Comparison Operators


In [11]:
x = 12
y = 10

# Greater Than Operator
print('x > y = ',x > y)

# Greater Than or Equal To
print('x >= y', x >= y)

# Lesser Than Operator
print('x < y = ',x < y)

# Lesser Than or Equal To
print('x <= y', x <= y)

# Equal To Operator
print('x == y ',x == y)

# Not Equal To
print('x != y', x != y)


x > y =  True
x >= y True
x < y =  False
x <= y False
x == y  False
x != y True

Logical Operators

and - True if both operands are true
or - True if one of the operand is true
not - True if operand is false 

Bitwise Operators

& -> Bitwise AND
| -> Bitwise OR
~ -> Bitwise NOT
^ -> Bitwise XOR
>> -> Bitwise Right Shift
<< -> Bitwise Left Shift

In [6]:
x = 10
y = 4

# Bitwise AND
print('x & y = ', x & y)
# Bitwise OR
print('x | y = ', x | y)
# Bitwise NOT
print('~ x = ', ~ x)
# Bitwise XOR
print('x ^ y = ', x ^ y)
# Right shift
print('x >> y = ', x >> y)
# Left Shift
print('x << y = ', x << y)


x & y =  0
x | y =  14
~ x =  -11
x ^ y =  14
x >> y =  0
x << y =  160

Assignment Operators


In [12]:
a = 5
print(a)
a += 5 # a = a + 5
print(a)
a -= 5 # a = a - 5 
print(a)
a *= 5 # a = a * 5
print(a)
a /= 5 # a = a / 5
print(a)
a //= 2 # a = a // 2
print(a)
a %= 1 # a = a % 1
print(a)
a = 10
a **= 2 # a = a ** 2
print(a)


5
10
5
25
5.0
2.0
0.0
100

Special Operators

Identity Operators
 is - True if the operands are identical
 is not - True if the operands are not identical
 

In [16]:
x1 = 2
y1 = 2
x2 = 'Hello'
y2 = "Hello"
x3 = [1,2,3]
y3 = (1,2,3)

print('x1 is y1 = ', x1 is y1)
print('x1 is y2 = ', x1 is y2)
print('x3 is not y3 = ', x3 is not y3)


x1 is y1 =  True
x1 is y2 =  False
x3 is not y3 =  True
Membership Operators
    in - True if value / variable is found in sequence
    not in - True if value / variable is not found in the sequence

In [17]:
x = 'Hello World'
y = {1:'a',2:'b'}

print("'H' in x ", 'H' in x)
print('hello not in x ','hello' not in x)
print('1 in y = ',1 in y)
print('a in y = ',a in y)


'H' in x  True
hello not in x  True
1 in y =  True
a in y =  False