Python Operators
Operators are special symbols that perform operations on variables and values. Python provides a rich set of operators organized into several categories.
Arithmetic Operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 10 + 3 | 13 |
- | Subtraction | 10 - 3 | 7 |
* | Multiplication | 10 * 3 | 30 |
/ | Division | 10 / 3 | 3.3333 |
// | Floor Division | 10 // 3 | 3 |
% | Modulus | 10 % 3 | 1 |
** | Exponentiation | 2 ** 10 | 1024 |
python
a, b = 17, 5
print(a + b) # 22
print(a - b) # 12
print(a * b) # 85
print(a / b) # 3.4
print(a // b) # 3 (floor division - rounds down)
print(a % b) # 2 (remainder)
print(a ** b) # 1419857 (17 to the power of 5)
# Negative floor division rounds toward negative infinity
print(-17 // 5) # -4 (not -3!)
print(-17 % 5) # 3Comparison Operators
Comparison operators return True or False:
| Operator | Name | Example | Result |
|---|---|---|---|
== | Equal | 5 == 5 | True |
!= | Not equal | 5 != 3 | True |
> | Greater than | 5 > 3 | True |
< | Less than | 5 < 3 | False |
>= | Greater or equal | 5 >= 5 | True |
<= | Less or equal | 5 <= 3 | False |
python
x, y = 10, 20
print(x == y) # False
print(x != y) # True
print(x > y) # False
print(x < y) # True
print(x >= 10) # True
print(x <= 5) # False
# Chained comparisons (unique to Python!)
age = 25
print(18 <= age <= 65) # True
print(1 < 2 < 3 < 4) # True
# String comparison (lexicographic)
print("apple" < "banana") # True
print("abc" == "abc") # TrueLogical Operators
| Operator | Description | Example | Result |
|---|---|---|---|
and | True if both are True | True and False | False |
or | True if at least one is True | True or False | True |
not | Reverses the result | not True | False |
python
x = 15
# Combining conditions
print(x > 10 and x < 20) # True
print(x > 20 or x < 10) # False
print(not (x > 20)) # True
# Short-circuit evaluation
# 'and' stops at first False, 'or' stops at first True
print(False and print("never runs")) # False (print not executed)
print(True or print("never runs")) # True (print not executed)
# Practical example
age = 25
has_license = True
if age >= 18 and has_license:
print("Can drive")Truthiness with and/or
and and or return the actual value, not just True/False:
python
# 'and' returns first falsy value or last value
print(1 and 2 and 3) # 3 (all truthy, returns last)
print(1 and 0 and 3) # 0 (first falsy)
print("" and "hello") # "" (first falsy)
# 'or' returns first truthy value or last value
print(0 or "" or "hello") # "hello" (first truthy)
print(0 or "" or []) # [] (all falsy, returns last)
# Common pattern: default values
name = "" or "Anonymous"
print(name) # Anonymous
port = None or 8080
print(port) # 8080Assignment Operators
| Operator | Example | Equivalent |
|---|---|---|
= | 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 |
%= | x %= 3 | x = x % 3 |
**= | x **= 3 | x = x ** 3 |
python
x = 10
x += 5 # x = 15
x -= 3 # x = 12
x *= 2 # x = 24
x //= 5 # x = 4
x **= 3 # x = 64
print(x) # 64
# Works with strings too
greeting = "Hello"
greeting += " World"
print(greeting) # Hello World
# Works with lists
items = [1, 2]
items += [3, 4]
print(items) # [1, 2, 3, 4]Walrus Operator := (Python 3.8+)
Assigns and returns a value in an expression:
python
# Without walrus operator
data = input("Enter data: ")
if len(data) > 10:
print(f"Too long: {len(data)} characters")
# With walrus operator
if (n := len(input("Enter data: "))) > 10:
print(f"Too long: {n} characters")
# Useful in while loops
while (line := input("Enter text (q to quit): ")) != "q":
print(f"You entered: {line}")
# In list comprehensions
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
results = [y for x in numbers if (y := x ** 2) > 25]
print(results) # [36, 49, 64, 81, 100]Identity Operators
| Operator | Description | Example |
|---|---|---|
is | Same object in memory | x is y |
is not | Different objects | x is not y |
python
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True (same value)
print(a is b) # False (different objects)
print(a is c) # True (same object)
print(a is not b) # True
# Always use 'is' with None
x = None
print(x is None) # True (correct)
print(x == None) # True (works but not recommended)Best Practice: Use is to compare with None, True, and False. Use == for value comparison.
Membership Operators
| Operator | Description | Example |
|---|---|---|
in | Value found in sequence | "a" in "abc" → True |
not in | Value not found | 4 not in [1,2,3] → True |
python
# In strings
print("Py" in "Python") # True
print("java" in "Python") # False
# In lists
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # True
print("grape" not in fruits) # True
# In dictionaries (checks keys by default)
user = {"name": "Alice", "age": 25}
print("name" in user) # True
print("email" in user) # False
print("Alice" in user.values()) # True
# In range
print(5 in range(10)) # True
print(15 in range(10)) # FalseBitwise Operators
| Operator | Name | Example | Result |
|---|---|---|---|
& | AND | 5 & 3 | 1 |
| | OR | 5 | 3 | 7 |
^ | XOR | 5 ^ 3 | 6 |
~ | NOT | ~5 | -6 |
<< | Left shift | 5 << 1 | 10 |
>> | Right shift | 5 >> 1 | 2 |
python
a = 0b1010 # 10
b = 0b1100 # 12
print(bin(a & b)) # 0b1000 (AND: 8)
print(bin(a | b)) # 0b1110 (OR: 14)
print(bin(a ^ b)) # 0b0110 (XOR: 6)
print(bin(~a)) # -0b1011 (NOT: -11)
print(bin(a << 2)) # 0b101000 (Left shift: 40)
print(bin(a >> 1)) # 0b101 (Right shift: 5)
# Practical: check if number is even/odd
num = 7
print("odd" if num & 1 else "even") # odd
# Practical: flags
READ = 0b100 # 4
WRITE = 0b010 # 2
EXECUTE = 0b001 # 1
permissions = READ | WRITE # 6 (read + write)
print(bool(permissions & READ)) # True
print(bool(permissions & EXECUTE)) # FalseOperator Precedence
From highest to lowest priority:
| Priority | Operator | Description |
|---|---|---|
| 1 | () | Parentheses |
| 2 | ** | Exponentiation |
| 3 | ~, +x, -x | Unary operators |
| 4 | *, /, //, % | Multiplication, division |
| 5 | +, - | Addition, subtraction |
| 6 | <<, >> | Bitwise shifts |
| 7 | & | Bitwise AND |
| 8 | ^ | Bitwise XOR |
| 9 | | | Bitwise OR |
| 10 | ==, !=, <, >, <=, >=, is, in | Comparisons |
| 11 | not | Logical NOT |
| 12 | and | Logical AND |
| 13 | or | Logical OR |
python
# Precedence matters!
print(2 + 3 * 4) # 14 (not 20)
print((2 + 3) * 4) # 20
print(2 ** 3 ** 2) # 512 (right-associative: 2^(3^2) = 2^9)
print((2 ** 3) ** 2) # 64
# When in doubt, use parentheses!
result = (a + b) * (c - d) / (e ** f)Summary
- Arithmetic:
+,-,*,/,//,%,**for math operations - Comparison:
==,!=,<,>,<=,>=return boolean values - Logical:
and,or,notfor combining conditions; support short-circuit evaluation - Assignment:
=,+=,-=, etc. for updating variables - Walrus operator (
:=) assigns and returns in expressions (Python 3.8+) - Identity:
is,is notfor comparing object identity (use withNone) - Membership:
in,not infor checking if a value exists in a collection - Bitwise:
&,|,^,~,<<,>>for bit-level operations - Use parentheses when operator precedence is ambiguous
Next, we'll learn about Python strings in depth.