Python Operators
Python Operators are used to perform operations on variables and
values.
Python divides the operators and grouped as following:
Python
Arithmetic operators
The following are the Arithmetic operators in Python:
>>> x = 10 >>> y = 5 >>> >>> x+y 15 >>> x-y 5 >>> x*y 50 >>> x/y 2.0 >>> x%y 0 >>> x ** y 100000 >>>
From the above example,
Python
Assignment operators
The following are the Assignment operators in Python
>>> x=5 >>> x+=3 >>> print (x) 8 >>> x-=3 >>> print(x) 5 >>> x*=5 >>> print (x) 25 >>> x/=5 >>> print (x) 5.0 >>> x=5 >>> x//=3 >>> print (x) 1 >>> x**=3 >>> print (x) 1 >>> x&=3 >>> print (x) 1 >>> x|=3 >>> print (x) 3 >>> x^=3 >>> print (x) 0 >>> x>>=3 >>> print (x) 0 >>> x<<=3 >>> print (x) 0
From the above example,
Python
Comparison operators
The following are the Comparison operators of Python
>>> x=10 >>> y=5 >>> x==y False >>> x!=y True >>> x>y True >>> x<y False >>> x>=y True >>> x<=y False >>>
From the above example,
Python
Logical operators
The following are the logical operators in Python
>>> x=5 >>> if x>3 and x<10: ... print("value of x lies between 3 and 10") ... value of x lies between 3 and 10 >>> >>> x=3 >>> if x<2 or x<5: ... print("value of x less than 2 or 5") ... value of x less than 2 or 5 >>> >>> x=15 >>> if not(x<3 and x<10): ... print("value of x is not less than 10") ... value of x is not less than 10 >>>
From the above example,
Python
Identity operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location. The following are the Identity operators in Python
>>> x=5 >>> y=10 >>> x is 5 True >>> x is y False >>> x is not y True >>>
From the above example,
Python
Membership operators
Membership operators are used to test if a sequence is presented in an object:
>>> x = ["apple", "banana"] >>> >>> print("banana" in x) True >>> >>> print("pineapple" not in x) True
From the above example,
Python
Bitwise operators
Bitwise operators are used to compare (binary) numbers:
>>> a = 60 # 60 = 0011 1100 >>> b = 13 # 13 = 0000 1101 >>> c = 0 >>> >>> c = a & b; # 12 = 0000 1100 >>> print ("Line 1 - Value of c is ", c) Line 1 - Value of c is 12 >>> >>> c = a | b; # 61 = 0011 1101 >>> print ("Line 2 - Value of c is ", c) Line 2 - Value of c is 61 >>> >>> c = a ^ b; # 49 = 0011 0001 >>> print ("Line 3 - Value of c is ", c) Line 3 - Value of c is 49 >>> >>> c = ~a; # -61 = 1100 0011 >>> print ("Line 4 - Value of c is ", c) Line 4 - Value of c is -61 >>> >>> c = a << 2; # 240 = 1111 0000 >>> print ("Line 5 - Value of c is ", c) Line 5 - Value of c is 240 >>> >>> c = a >> 2; # 15 = 0000 1111 >>> print ("Line 6 - Value of c is ", c) Line 6 - Value of c is 15 >>>
From the above example,