Chapter 4: Python Operators
1. Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common
mathematical operations:
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
2. Python Assignment Operators
Assignment operators are used to assign values to variables:
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
16
3. Python Comparison Operators
Comparison operators are used to compare two values:
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
4. Python Logical Operators
Logical operators are used to combine conditional statements:
Operator Description Example
Returns True if both statements
and x < 5 and x < 10
are true
Returns True if one of the
or x < 5 or x < 4
statements is true
Reverse the result, returns False if
not not(x < 5 and x < 10)
the result is true
5. 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:
Operator Description Example
Returns True if both variables
is x is y
are the same object
Returns True if both variables
is not x is not y
are not the same object
17
6. Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
Operator Description Example
Returns True if a sequence with the specified
In x in y
value is present in the object
Returns True if a sequence with the specified
not in x not in y
value is not present in the object
7. Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
Operator Name Description Example
Sets each bit to 1
& AND x&y
if both bits are 1
Sets each bit to 1
| OR x|y
if one of two bits is 1
Sets each bit to 1
^ XOR x^y
if only one of two bits is 1
~ NOT Inverts all the bits ~x
18