By: Archana Shukla and Rajesh Shukla
Comparison operators:(==,!=,>,<,>=,<=,)
Operator | Meaning | Example | |
> | Greater than – True if left operand is greater than the right | x>y | >>>x=37 >>>y=28 >>>print(x>y) True |
< | Less than – True if left operand is less than the right | x<y | >>>x=10 >>>y=20 >>>print(x<y) True |
== | Equal to – True if both operands are equal | x==y | >>>x=8 >>>y=9 >>>print(x==y) False |
!= | Not equal to – True if operands are not equal | x!=y | >>>x=8 >>>y=9 >>>print(x!=y) True |
>= | Greater than or equal to – True if left operand is greater than or equal to the right | x>=y | >>>x=9 >>>y=8 >>>print(x>=y) True |
<= | Less than or equal to – True if left operand is less than or equal to the right | x<=y | >>>x=8 >>>y=9 >>>print(x<=y) True |
Logical operators: (and, or, not)
Operator | Meaning | Example | |
and | True if both the operands are true | xandy | >>>x=6 >>>y=8 >>>print(x>3 and y>5) True |
or | True if either of the operands is true | x or y | >>>x=6 >>>y=8 >>>print(x>3 or y>10) True |
not | True if the operand is false (complements the operand) | not x | >>>x=2 >>>y=3 >>>print(not(x>y)) True |
Identity operators:(is, is not)
“is” and “is not” are the identity operators in Python. They are used to check if two values (or variables) are located on the same part of the memory. Two variables that are equal does not imply that they are identical.
Example:
>> x=5
>>> y=5
>>> print(x is y)
True
>>> print(x is not y)
False
Example:
x3 = [1,2,3]
y3 = [1,2,3]
print(x3 is y3)
# Output: False
print(x3 is not y3)
# Output: True
Note : Both x3 and y3 are list. They are equal but not identical. Since list are mutable (can be changed), interpreter locates them separately in memory although they are equal.
Membership operators (in, not in):
“in” and “not in” are the membership operators in Python. They are used to test whether a value or variable is found in a sequence (string, list, tuple, set and dictionary).
Example:1
x = ‘Hello world’
print(‘H’ in x)
# Output: True
print(‘hello’ not in x)
# Output: True
print(‘w’ in x)
# Output: True
print(‘Hello’ in x)
# Output: True
Here, ‘H’ is in x but ‘hello’ is not present in x (remember, Python is case sensitive).
In a dictionary we can only test for presence of key, not the value.
>>> y = {1:’a’,2:’b’}
Here 1 is key and ‘a’ is the value in dictionary y.
Here 2 is key and ‘b’ is the value in dictionary y.
We can check for key and not value.
>>> print(1 in y)
True
>>> print(‘a’ in y)
False