OPERATORS
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
ARITHMETIC OPERATORS
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication and division.
There are 7 arithmetic operators in Python :
Addition
Subtraction
Multiplication
Division
Modulus
Exponentiation
Floor division
1. Addition Operator : In Python, + is the addition operator. It is used to add 2 values.
Example :
val1 = 2
val2 = 3
# using the addition operator
res = val1 + val2
print(res)
Output :
5
2. Subtraction Operator : In Python, – is the subtraction operator. It is used to subtract the second value from the first value.
Example :
val1 = 2
val2 = 3
# using the subtraction operator
res = val1 - val2
print(res)
Output :
-1
3. Multiplication Operator : In Python, * is the multiplication operator. It is used to find the product of 2 values.
Example :
val1 = 2
val2 = 3
# using the multiplication operator
res = val1 * val2
print(res)
Output :
6
4. Division Operator : In Python, / is the division operator. It is used to find the quotient when first operand is divided by the second.
Example :
val1 = 3
val2 = 2
# using the division operator
res = val1 / val2
print(res)
Output :
1.5
5. Modulus Operator : In Python, % is the modulus operator. It is used to find the remainder when first operand is divided by the second.
Example :
val1 = 3
val2 = 2
# using the modulus operator
res = val1 % val2
print(res)
Output :
1
6. Exponentiation Operator : In Python, ** is the exponentiation operator. It is used to raise the first operand to power of second.
Example :
val1 = 2
val2 = 3
# using the exponentiation operator
res = val1 ** val2
print(res)
Output :
8
7. Floor division : In Python, // is used to conduct the floor division. It is used to find the floorof the quotient when first operand is divided by the second.
Example :
val1 = 3
val2 = 2
# using the floor division
res = val1 // val2
print(res)
Output :
1
1) Assign: This operator is used to assign the value of the right side of the expression to the left side operand.
Syntax:
x = y + z
Example:
# Assigning values using
# Assignment Operator
a = 3
b = 5
c = a + b
# Output
print(c)
Output:
8
2) Add and Assign: This operator is used to add the right side operand with the left side operand and then assigning the result to the left operand.
Syntax:
x += y
Example:
a = 3
b = 5
# a = a + b
a += b
# Output
print(a)
Output:
8
3) Subtract and Assign: This operator is used to subtract the right operand from the left operand and then assigning the result to the left operand.
Syntax:
x -= y
Example –
a = 3
b = 5
# a = a - b
a -= b
# Output
print(a)
Output:
-2
4) Multiply and Assign: This operator is used to multiply the right operand with the left operand and then assigning the result to the left operand.
Syntax:
x *= y
Example:
a = 3
b = 5
# a = a * b
a *= b
# Output
print(a)
Output:
15
5) Divide and Assign: This operator is used to divide the left operand with the right operand and then assigning the result to the left operand.
Syntax:
x /= y
Example:
a = 3
b = 5
# a = a / b
a /= b
# Output
print(a)
Output:
0.6
6) Modulus and Assign: This operator is used to take the modulus using the left and the right operands and then assigning the result to the left operand.
Syntax:
x %= y
Example:
a = 3
b = 5
# a = a % b
a %= b
# Output
print(a)
Output:
3
7) Divide (floor) and Assign: This operator is used to divide the left operand with the right operand and then assigning the result(floor) to the left operand.
Syntax:
x //= y
Example:
a = 3
b = 5
# a = a // b
a //= b
# Output
print(a)
Output:
0
8) Exponent and Assign: This operator is used to calculate the exponent(raise power) value using operands and then assigning the result to the left operand.
Syntax:
x **= y
Example:
a = 3
b = 5
# a = a ** b
a **= b
# Output
print(a)
Output:
243
9) Bitwise AND and Assign: This operator is used to perform Bitwise AND on both operands and then assigning the result to the left operand.
Syntax:
x &= y
Example:
a = 3
b = 5
# a = a & b
a &= b
# Output
print(a)
Output:
1
10) Bitwise OR and Assign: This operator is used to perform Bitwise OR on the operands and then assigning result to the left operand.
Syntax:
x |= y
Example:
a = 3
b = 5
# a = a | b
a |= b
# Output
print(a)
Output:
7
11) Bitwise XOR and Assign: This operator is used to perform Bitwise XOR on the operands and then assigning result to the left operand.
Syntax:
x ^= y
Example:
a = 3
b = 5
# a = a ^ b
a ^= b
# Output
print(a)
Output:
6
12) Bitwise Right Shift and Assign: This operator is used to perform Bitwise right shift on the operands and then assigning result to the left operand.
Syntax:
x >>= y
Example:
a = 3
b = 5
# a = a >> b
a >>= b
# Output
print(a)
Output:
0
13) Bitwise Left Shift and Assign: This operator is used to perform Bitwise left shift on the operands and then assigning result to the left operand.
Syntax:
x <<= y
Example:
a = 3
b = 5
# a = a << b
a <<= b
# Output
print(a)
Output:
96
There are 6 types of comparison operators :
Yahoo Answers to Shut Down Permanently in May
Less Than ( < )
Greater Than ( > )
Equal To ( == )
Not Equal ( != )
Less Than or Equal To ( <= )
Greater Than or Equal To ( >= )
Python Comparison Operators
It is used to check for the smaller value or variable containing smaller value as compared with the other number or variable. If the provided number or a variable is smaller than the given number or variable. Then, the Less Than operator will return True. Else, it will return false.
a = 10
if (a < 10)
print("Yes")
else
print("No")
Output: No
It is used to check for the greater value or variable containing greater value as compared with the other number or variable. If the provided number or a variable is greater than the given number or variable. Then, the Greater Than operator will return True. Else, it will return false.
a = 10
if (a > 10)
print("True")
else
print("False")
Output: False
This Operator checks for equal values. If the entered value and given value are equal then it will return True else False.
a = 10
b = 20
if (a == b)
print("True")
else
print("False")
Output: False
It is denoted by !=, this does the exact opposite of the equal to operator. It returns True if the values on either side of the operator are unequal.
print(3!=3.0)
Output: False
This operator evaluates to True only if the value on the left is less than or equal to that on the right.
a = 15
b = 5
if(b <= a)
print("b is either less than or equal to a")
Output: b is either less than or equal to a
This operator evaluates to True only if the value on the left is greater than or equal to that on the right.
a = 5
b = 15
if(b >= a)
print("b is either greater than or equal to a")
Output: b is either greater than or equal to a
Membership operators are operators used to validate the membership of a value. It test for membership in a sequence, such as strings, lists, or tuples.
in operator : The ‘in’ operator is used to check if a value exists in a sequence or not. Evaluates to true if it finds a variable in the specified sequence and false otherwise.
# Python program to illustrate
# Finding common member in list
# using 'in' operator
list1=[1,2,3,4,5]
list2=[6,7,8,9]
for item in list1:
if item in list2:
print("overlapping")
else:
print("not overlapping")
Output:
not overlapping
Same example without using in operator:
# Python program to illustrate
# Finding common member in list
# without using 'in' operator
# Define a function() that takes two lists
def overlapping(list1,list2):
c=0
d=0
for i in list1:
c+=1
for i in list2:
d+=1
for i in range(0,c):
for j in range(0,d):
if(list1[i]==list2[j]):
return 1
return 0
list1=[1,2,3,4,5]
list2=[6,7,8,9]
if(overlapping(list1,list2)):
print("overlapping")
else:
print("not overlapping")
Output:
not overlapping
‘not in’ operator- Evaluates to true if it does not finds a variable in the specified sequence and false otherwise.
# Python program to illustrate
# not 'in' operator
x = 24
y = 20
list = [10, 20, 30, 40, 50 ];
if ( x not in list ):
print("x is NOT present in given list")
else:
print("x is present in given list")
if ( y in list ):
print("y is present in given list")
else:
print("y is NOT present in given list")
Identity operators
n Python are used to determine whether a value is of a certain class or type. They are usually used to determine the type of data a certain variable contains.
There are different identity operators such as
‘is’ operator – Evaluates to true if the variables on either side of the operator point to the same object and false otherwise.
# Python program to illustrate the use
# of 'is' identity operator
x = 5
if (type(x) is int):
print("true")
else:
print("false")
Output:
true
‘is not’ operator – Evaluates to false if the variables on either side of the operator point to the same object and true otherwise.
# Python program to illustrate the
# use of 'is not' identity operator
x = 5.2
if (type(x) is not int):
print("true")
else:
print("false")
Output:
true
Bitwise AND operator: Returns 1 if both the bits are 1 else 0.
Example:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary
a & b = 1010
&
0100
= 0000
= 0 (Decimal)
Bitwise or operator: Returns 1 if either of the bit is 1 else 0.
Example:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary
a | b = 1010
|
0100
= 1110
= 14 (Decimal)
Bitwise not operator: Returns one’s compliement of the number.
Example:
a = 10 = 1010 (Binary)
~a = ~1010
= -(1010 + 1)
= -(1011)
= -11 (Decimal)
Bitwise xor operator: Returns 1 if one of the bit is 1 and other is 0 else returns false.
Example:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary
a & b = 1010
^
0100
= 1110
= 14 (Decimal)
# Python program to show
# bitwise operators
a = 10
b = 4
# Print bitwise AND operation
print("a & b =", a & b)
# Print bitwise OR operation
print("a | b =", a | b)
# Print bitwise NOT operation
print("~a =", ~a)
# print bitwise XOR operation
print("a ^ b =", a ^ b)
Output:
a & b = 0
a | b = 14
~a = -11
a ^ b = 14
These operators are used to shift the bits of a number left or right thereby multiplying or dividing the number by two respectively. They can be used when we have to multiply or divide a number by two.
Bitwise right shift: Shifts the bits of the number to the right and fills 0 on voids left as a result. Similar effect as of dividing the number with some power of two.
Example:
Example 1:
a = 10
a >> 1 = 5
Example 2:
a = -10
a >> 1 = -5
Bitwise left shift: Shifts the bits of the number to the left and fills 0 on voids left as a result. Similar effect as of multiplying the number with some power of two.
Example:
a = 5 = 0000 0101
b = -10 = 1111 0110
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20
b << 1 = 0000 1010 = -20
b << 2 = 0001 0100 = -40
# Python program to show
# shift operators
a = 10
b = -10
# print bitwise right shift operator
print("a >> 1 =", a >> 1)
print("b >> 1 =", b >> 1)
a = 5
b = -10
# print bitwise left shift operator
print("a << 1 =", a << 1)
print("b << 1 =", b << 1)
Output:
a >> 1 = 5
b >> 1 = -5
a << 1 = 10
b << 1 = -20
Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because ‘+’ operator is overloaded by int class and str class. You might have noticed that the same built-in operator or function shows different behavior for objects of different classes, this is called Operator Overloading.
Below is a simple example of Bitwise operator overloading.
# Python program to demonstrate
# operator overloading
class Geek():
def __init__(self, value):
self.value = value
def __and__(self, obj):
print("And operator overloaded")
if isinstance(obj, Geek):
return self.value & obj.value
else:
raise ValueError("Must be a object of class Geek")
def __or__(self, obj):
print("Or operator overloaded")
if isinstance(obj, Geek):
return self.value | obj.value
else:
raise ValueError("Must be a object of class Geek")
def __xor__(self, obj):
print("Xor operator overloaded")
if isinstance(obj, Geek):
return self.value ^ obj.value
else:
raise ValueError("Must be a object of class Geek")
def __lshift__(self, obj):
print("lshift operator overloaded")
if isinstance(obj, Geek):
return self.value << obj.value
else:
raise ValueError("Must be a object of class Geek")
def __rshift__(self, obj):
print("rshift operator overloaded")
if isinstance(obj, Geek):
return self.value & obj.value
else:
raise ValueError("Must be a object of class Geek")
def __invert__(self):
print("Invert operator overloaded")
return ~self.value
# Driver's code
if __name__ == "__main__":
a = Geek(10)
b = Geek(12)
print(a & b)
print(a | b)
print(a ^ b)
print(a << b)
print(a >> b)
print(~a)
Output:
And operator overloaded
8
Or operator overloaded
14
Xor operator overloaded
8
lshift operator overloaded
40960
rshift operator overloaded
8
Invert operator overloaded
-11
BOOLEAN
Booleans represent one of two values: True or False.
In programming you often need to know if an expression is True or False.
You can evaluate any expression in Python, and get one of two answers, True or False.
When you compare two values, the expression is evaluated and Python returns the Boolean answer:
print(10 > 9)
print(10 == 9)
print(10 < 9)
When you run a condition in an if statement, Python returns True or False:
Print a message based on whether the condition is True or False:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
The bool() function allows you to evaluate any value, and give you True or False in return,
Evaluate a string and a number:
print(bool("Hello"))
print(bool(15))
Evaluate two variables:
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
Almost any value is evaluated to True if it has some sort of content.
Any string is True, except empty strings.
Any number is True, except 0.
Any list, tuple, set, and dictionary are True, except empty ones.
The following will return True:
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
In fact, there are not many values that evaluate to False, except empty values, such as (), [], {}, "", the number 0, and the value None. And of course the value False evaluates to False.
The following will return False:
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
One more value, or object in this case, evaluates to False, and that is if you have an object that is made from a class with a __len__ function that returns 0 or False:
class myclass():
def __len__(self):
return 0
myobj = myclass()
print(bool(myobj))
You can create functions that returns a Boolean Value:
Print the answer of a function:
def myFunction() :
return True
print(myFunction())
You can execute code based on the Boolean answer of a function:
Print "YES!" if the function returns True, otherwise print "NO!":
def myFunction() :
return True
if myFunction():
print("YES!")
else:
print("NO!")
Python also has many built-in functions that return a boolean value, like the isinstance() function, which can be used to determine if an object is of a certain data type:
Check if an object is an integer or not:
x = 200
print(isinstance(x, int))