Types of Operators in Python
We have different types of operators in Python to perform operations on values and variables in Python.
There are 7 types of operators used in almost all programming languages.
- Assignment operators
- Arithmetic operators
- Comparison operators
- Logical operators
- Identity operators
- Membership operators
- Bitwise operator
Assignment Operators
Assignment operators will work for us when we have to assign values to variables.
Operators | Example | Alternative |
= | x=5 | x=5 |
+= | x+=5 | x=x+5 |
-= | X-=5 | x=x-5 |
*= | x*=5 | x=x*5 |
/= | x/=5 | x=x/5 |
%= | X %=5 | x=x%5 |
//= | x//=5 | x=x//5 |
**= | x**=3 | x=x**5 |
&= | X &=5 | x=x&5 |
!= | x! =5 | x=x|5 |
^= | x^=5 | x=x^5 |
>>= | x=x>>=5 | x=x>>5 |
<<= | x<<=5 | x=x<<5 |
Arithmetic Operators
We can apply arithmetic operators on numeric values to perform some mathematical operations:
Operators | Name | Example |
+ | Addition | x+ y |
– | Subtraction | x- y |
* | Multiplication | x* y |
/ | Division | x/ y |
% | Modulus | x% y |
** | Exponentiation | x** y |
// | Floor Division | x//y |
Comparison Operator
We can compare two values by using comparison operators.
Operators | Name | Example |
== | Equal operator | x== y |
!= | Not operator | x! = y |
> | Greater operator | x> y |
< | Less than operator | x< y |
>= | Less than or equal to the operator | x>= y |
<= | Less than or equal to operator | x<= y |
Logical Operators
Operator | Description | Example |
and | Return True if both statements are true | x<20 and x<50 |
or | Returns True if one of the statements is true | x<20 or x<10 |
not | Reverse the result, returns False if the result is true | not (x<5 and x<10) |
Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are the same object, with the same memory location:
Operator | Description | Example |
is | Returns true if both variables are the same object | x is y |
is not | Returns true if both variables are not the same object | x is not y |
Membership Operators
Membership operators are used to test if a sequence is presented in an object:
Operator | Description | Example |
in | Returns True if a sequence with the specified value is present in the object | x in y |
not in | Returns True if a sequence with the specified value is not present in the object | x not in y |
Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
Operators | Name | Description |
& | AND | Sets each bit to 1 if both bits are 1 |
| | OR | Set each bit to 1 if one of two bits is 1. |
^ | XOR | Set each bit to 1 if only one of two bits is 1. |
~ | NOT | Invert all the bits |
<< | Zero fill left shift | Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off. |
>> | Signed right shift | Zero-fill left shift |
Author: TCF Editorial
Copyright The Cloudflare.