Advertisement
❮ Previous: Python Booleans Next: Python If...Else & Conditional Expressions ❯

Python Operators

Python operators are special symbols used to perform operations on variables and values. Python divides operators into several major groups according to their functionality.


1. Arithmetic Operators

Used with numeric values to perform common mathematical operations.

Operator Name Example Result
+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division 10 / 3 3.3333333333333335
// Floor Division 10 // 3 3 (rounds down to nearest integer)
% Modulus (Remainder) 10 % 3 1
** Exponentiation 2 ** 3 8 (23)

Advertisement

2. Comparison (Relational) Operators

Used to compare two values. They always return a Boolean value (True or False).

Operator Name Example (a = 5, b = 10) Result
== Equal a == b False
!= Not equal a != b True
> Greater than b > a True
< Less than a < b True
>= Greater than or equal to b >= 10 True
<= Less than or equal to a <= 5 True

Advertisement

3. Logical Operators

Used to combine conditional statements.

Operator Description Example Result
and Returns True if both statements are true (5 > 3) and (10 > 5) True
or Returns True if at least one statement is true (5 > 3) or (10 < 5) True
not Reverse the result, returns False if result is true not(5 > 3) False

Advertisement

4. Bitwise Operators

Used to compare (binary) numbers bit by bit.

Operator Name Description Example (x = 2 [10], y = 3 [11])
& AND Sets each bit to 1 if both bits are 1 2 & 3 --> 2 (10 & 11 = 10)
` ` 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 2 ^ 3 --> 1 (10 ^ 11 = 01)
~ NOT Inverts all the bits ~2 --> -3
<< Zero fill left shift Shift left by pushing zeros in from the right 2 << 1 --> 4 (10 becomes 100)
>> Signed right shift Shift right by pushing copies of the leftmost bit 2 >> 1 --> 1 (10 becomes 1)

Advertisement

5. Assignment Operators

Used to assign values to variables, often combined with an arithmetic operation.

Operator Equivalent Example
= x = 5 x = 5
+= x = x + 3 x += 3 (x becomes 8)
-= x = x - 3 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 x **= 3

Try this code ❯


Advertisement

6. Bonus: Identity & Membership Operators

x = ["apple", "banana"]
y = ["apple", "banana"]
z = x
print(x is z)  # True (same object in memory)
print(x is y)  # False (different objects, even if contents match)

Try this code ❯

fruits = ["apple", "banana", "cherry"]
print("banana" in fruits)      # True
print("grape" not in fruits)   # True

Try this code ❯

❮ Previous: Python Booleans Next: Python If...Else & Conditional Expressions ❯
Advertisement