Learning Python

9. Operators

9.1. Arithmetic operators

Operator Name Example
+ Addition x + y
Subtraction x – y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y

9.2. Comparison operators

Operator Name Example
Equal x y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

9.3. Logical operators

Operator Description Example
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

9.4. Identity operators

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

9.5. Membership operators

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

9.6. Bitwise operators

Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

9.7. Assignment operators

Operator Description Example Long form
= Assignment x = 2 x = 2
+= Arithmetic Addition x += 2 x = x + 2
-= Arithmetic Subtraction x -= 2 x = x – 2
*= Arithmetic Multiplication x *= 2 x = x * 2
/= Arithmetic Division x /= 2 x = x / 2
%= Arithmetic Modulus x %= 2 x = x % 2
//= Arithmetic Exponentiation x //= 2 x = x // 2
**= Arithmetic Floor division x **= 2 x = x ** 2
&= Bitwise AND x &= 2 x = x & 2
|= Bitwise OR x |= 2 x = x | 2
^= Bitwise XOR x ^= 2 x = x ^ 2
>>= Bitwise Shift Left x >>= 2 x = x >> 2
<<= Bitwise Shift Right x <<= 2 x = x << 2