We have different types of operators in Python, such as Arithmetic, Assignment, Logical, Comparison (relational), Bitwise, Identity, and membership operators. Before going into the details of Python Operators, let’s have a glance over some of the essential topics which could help us in a better understanding of the entire Operators topic.
There are following Bitwise operators supported by Python language.
Operator | Description | Example |
---|---|---|
& Binary AND | Operator copies a bit to the result if it exists in both operands | (a & b) (means 0000 1100) |
| Binary OR | It copies a bit if it exists in either operand. | (a | b) = 61 (means 0011 1101) |
^ Binary XOR | It copies the bit if it is set in one operand but not both. | (a ^ b) = 49 (means 0011 0001) |
~ Binary Ones Complement | It is unary and has the effect of 'flipping' bits. | (~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number. |
<< Binary Left Shift | The left operands value is moved left by the number of bits specified by the right operand. | a << 2 = 240 (means 1111 0000) |
>> Binary Right Shift | The left operands value is moved right by the number of bits specified by the right operand. | a >> 2 = 15 (means 0000 1111) |
Example
Live DemoWhen you execute the above program it produces the following result −
The following table lists all operators from highest precedence to lowest.
Operator | Description |
---|---|
** | Exponentiation (raise to the power) |
~ + - | Complement, unary plus and minus (method names for the last two are +@ and -@) |
* / % // | Multiply, divide, modulo and floor division |
+ - | Addition and subtraction |
>> << | Right and left bitwise shift |
& | Bitwise 'AND'td> |
^ | | Bitwise exclusive `OR' and regular `OR' |
<= < > >= | Comparison operators |
<> != | Equality operators |
= %= /= //= -= += *= **= | Assignment operators |
is is not | Identity operators |
in not in | Membership operators |
not or and | Logical operators |
Operator precedence affects how an expression is evaluated.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first multiplies 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom.
Example
Live DemoWhen you execute the above program, it produces the following result −
python_basic_operators.htm