There are five groups of operators in the Python programming language: arithmetic, comparison, assignment, logical, identity, membership, and bitwise.
- Arithmetic operators - are used to perform basic mathematical operations
- Comparison operators - are used to compare values, they return a True/False based on the statement
- Assignment operators - are used to perform some operation and assign a value to a variable
- Logical operators - are used to combine conditional statements
- Identity operators - are used to determine if objects are the same
- Membership operators - are used to determine if a value is found in a sequence
- Bitwise operators - are used to perform operations at the bit level
Arithmetic Operators
-
+: Addition -
-: Subtraction -
*: Multiplication -
/: Division -
//: Floor division - round down division -
%: Modulo operation - remainder from division -
**: Power operation
>>> 8 + 3
11
>>> 8 - 3
5
>>> 8 * 3
24
>>> 8 /3
2.6666666666666665
>>> 16//3
5
>>> 16%3
1
>>> 2**3
8
Order of operation
In Python, just like in Math order of arithmetic operations is governed by PEMDAS - Parentheses, Exponent, Multiplication, Division, Addition, Subtraction.
>>> 3 + 2 * 8
19
>>> (3 + 2) * 8
40
Comparison Operators
-
==: Equal -
!=: Not equal -
>: Greater than -
<: Less than -
>=: Greater than or equal -
<=: Less than or equal
>>> a = 3
>>> b = 8
>>> a == b
False
>>> a != b
True
>>> a > b
False
>>> a < b
True
>>> a >= b
False
>>> a <= b
True
Assignment Operators
-
=: Assignment -
+=: Addition assignment -
-=: Subtraction assignment -
*=: Multiplication assignment -
/=: Division assignment -
%=: Modulus assignment -
//=: Floor division assignment -
**=: Power assignment -
&=: Bitwise AND assignment -
|=: Bitwise OR assignment -
^=: Bitwise XOR assignment -
>>=: Bitwise shift right assignment -
<<=: Bitwise shift left assignment
Logical Operators
-
and: And logical operation -
or: Or logical operation -
not: Not logical operation
>>> 5 > 3 and 2 > 1
True
>>> 5 > 3 or 2 > 5
True
>>> not(5 > 3)
False
Identity Operators
-
is: Is the same object -
is not: Is not the same object
>>> x = [1, 2]
>>> y = [1, 2]
>>> x is y
False
>>> x is not y
True
Membership Operators
-
in: And logical operation -
not in: Or logical operation
>>> 5 in [3, 5, 8]
True
>>> 5 not in [3, 5, 8]
False
Bitwise Operators
-
&: Bitwise AND -
|: Bitwise OR -
^: Bitwise XOR -
>>: Bitwise shift right -
<<: Bitwise shift left
>>> 9 & 3
1
>>> 9 | 3
11
>>> 9 ^ 3
10
>>> 9 << 2
36
>>> 9 >> 2
2
Combining Operators
You can combine the various operators above in various ways, such as:
>>> x = 3
>>> (x < 5 + 1) and (x > 1)
True
Top comments (0)