Skip to main content

Python Operators Explained: Types, Examples, and Usage

Calculating read time…

You've learned about variables and data types — now it's time to discover how to actually DO things with that data. Operators are the action words of programming: if variables are the nouns (the "things"), operators are the verbs — the actions you perform on those things. This guide covers all seven categories of Python operators with real, runnable examples. ⚙️

Why does this matter beyond syntax? Because most beginner bugs — an if that never fires, a loop that runs forever, a calculation that's silently wrong — trace back to a misunderstood operator: = instead of ==, integer division where you expected a decimal, or precedence you didn't account for. Get operators solid now, and entire categories of bugs disappear later. 🛡️

🔧 What Are Operators?

An operator is a symbol that tells Python to perform a specific operation. Just like in mathematics, where + means "add these numbers together," Python operators tell the computer what action to take.

📌 What this code does: adds two numbers together and stores the result, then labels each part of the expression — the "operands" being acted on, and the "operator" performing the action.
# Simple example
result = 5 + 3

# Breaking it down:
# 5 and 3 are "operands" (the things being operated on)
# + is the "operator" (the action to perform)
# result is where we store the answer

The Big Picture

Python has seven main categories of operators:

  1. Arithmetic Operators — math operations (+, -, *, /)
  2. Comparison Operators — compare values (==, !=, >, <)
  3. Logical Operators — combine conditions (and, or, not)
  4. Assignment Operators — assign values (=, +=, -=)
  5. Bitwise Operators — binary operations (&, |, ^)
  6. Identity Operators — check object identity (is, is not)
  7. Membership Operators — check membership (in, not in)

Don't worry if this seems like a lot — we'll explore each category with clear, runnable examples.

➕ 1. Arithmetic Operators: The Mathematics of Python

These are the operators you use for calculations. If you can use a calculator, you already understand most of these.

Addition (+)

📌 What this code does: adds two plain numbers, then adds two variables representing a price and tax, then chains four numbers together in one expression.
# Basic addition
result = 10 + 5
print(result)  # Output: 15

# Adding variables
price = 19.99
tax = 2.50
total = price + tax
print(f"Total: ${total}")  # Output: Total: $22.49

# Adding multiple values
sum_total = 10 + 20 + 30 + 40
print(sum_total)  # Output: 100
✅ Bonus: String Concatenation
The + operator also works with strings!
first_name = "Alice"
last_name = "Smith"
full_name = first_name + " " + last_name
print(full_name)  # Output: Alice Smith

Subtraction (-)

📌 What this code does: subtracts one number from another, calculates change from a cash payment, and shows that negative results are perfectly valid.
# Basic subtraction
result = 10 - 5
print(result)  # Output: 5

# Practical example: Calculate change
paid = 50
cost = 37.25
change = paid - cost
print(f"Your change: ${change}")  # Output: Your change: $12.75

# Negative results are allowed
result = 5 - 10
print(result)  # Output: -5

Multiplication (*)

📌 What this code does: multiplies two numbers, calculates a total price from a unit price and quantity, and multiplies by a decimal.
# Basic multiplication
result = 6 * 7
print(result)  # Output: 42

# Practical example: Calculate total price
item_price = 15.99
quantity = 3
total = item_price * quantity
print(f"Total: ${total}")  # Output: Total: $47.97

# Multiplying by decimals
result = 10 * 2.5
print(result)  # Output: 25.0
✅ Bonus: String Repetition
Multiply strings to repeat them!
laugh = "ha" * 3
print(laugh)  # Output: hahaha

line = "=" * 40
print(line)   # Output: ========================================

Division (/)

Divides one number by another. Always returns a float, even if the result is a whole number.

📌 What this code does: divides numbers and confirms the result type is always float, then splits a restaurant bill evenly among a group.
# Basic division
result = 10 / 2
print(result)        # Output: 5.0 (notice the .0)
print(type(result))  # Output: <class 'float'>

# Division with remainder
result = 10 / 3
print(result)  # Output: 3.3333333333333335

# Practical example: Split bill
total_bill = 150
people = 4
per_person = total_bill / people
print(f"Each person pays: ${per_person}")  # Output: Each person pays: $37.5
❌ Division by Zero Error
result = 10 / 0  # Error! ZeroDivisionError

# Always check before dividing:
divisor = 0
if divisor != 0:
    result = 10 / divisor
else:
    print("Cannot divide by zero!")

Floor Division (//)

Divides and rounds DOWN to the nearest whole number. Removes the decimal part.

📌 What this code does: compares floor division against regular division, calculates how many full boxes fit a quantity of items, and shows how negative numbers round toward negative infinity, not zero.
# Basic floor division
result = 10 // 3
print(result)  # Output: 3 (not 3.333...)

# Compare with regular division
print(10 / 3)   # Output: 3.3333333333333335
print(10 // 3)  # Output: 3

# Practical example: How many full boxes?
items = 47
box_capacity = 12
full_boxes = items // box_capacity
print(f"Full boxes: {full_boxes}")  # Output: Full boxes: 3

# Works with negative numbers (rounds DOWN, not towards zero)
print(-10 // 3)  # Output: -4 (not -3!)

Modulus (%)

Returns the remainder after division — super useful for checking divisibility.

📌 What this code does: calculates remainders, uses that remainder to detect even numbers, and calculates leftover items that don't fill a complete box.
# Basic modulus
result = 10 % 3
print(result)  # Output: 1 (10 ÷ 3 = 3 remainder 1)

result = 15 % 4
print(result)  # Output: 3 (15 ÷ 4 = 3 remainder 3)

# Check if number is even
number = 42
if number % 2 == 0:
    print("Even number!")  # This prints
else:
    print("Odd number!")

# Practical example: Calculate leftover items
items = 47
box_capacity = 12
leftovers = items % box_capacity
print(f"Items that don't fit: {leftovers}")  
# Output: Items that don't fit: 11
💡 Modulus Use Cases:
  • Check if number is even/odd: n % 2 == 0
  • Cycle through values: index % list_length
  • Check divisibility: n % 5 == 0 (divisible by 5)
  • Get last digit: number % 10

Exponentiation (**)

Raises a number to a power — like using the ^ button on a calculator.

📌 What this code does: raises numbers to a power, computes a square root using a fractional exponent, and models compound interest growing over 10 years.
# Basic exponentiation
result = 2 ** 3
print(result)  # Output: 8 (2³ = 2 × 2 × 2)

result = 5 ** 2
print(result)  # Output: 25 (5² = 5 × 5)

# Square root using fractional exponents
result = 16 ** 0.5
print(result)  # Output: 4.0 (√16)

# Practical example: Compound interest
principal = 1000
rate = 1.05  # 5% interest
years = 10
final_amount = principal * (rate ** years)
print(f"After {years} years: ${final_amount:.2f}")
# Output: After 10 years: $1628.89

Arithmetic Operators Summary Table

Operator Name Example Result
+Addition10 + 515
-Subtraction10 - 55
*Multiplication10 * 550
/Division10 / 33.333...
//Floor Division10 // 33
%Modulus10 % 31
**Exponentiation2 ** 38

Real-World Example: Shopping Cart Calculator

📌 What this code does: calculates line-item totals for three products, sums them into a subtotal, applies 8% tax, and prints a full itemized receipt.
print("=== Shopping Cart Calculator ===\n")

# Item prices
laptop_price = 899.99
mouse_price = 24.99
keyboard_price = 79.99

# Quantities
laptop_qty = 1
mouse_qty = 2
keyboard_qty = 1

# Calculate subtotals
laptop_total = laptop_price * laptop_qty
mouse_total = mouse_price * mouse_qty
keyboard_total = keyboard_price * keyboard_qty

# Calculate cart total
subtotal = laptop_total + mouse_total + keyboard_total

# Apply tax (8%)
tax = subtotal * 0.08

# Calculate final total
total = subtotal + tax

# Display receipt
print(f"Laptop x{laptop_qty}: ${laptop_total:.2f}")
print(f"Mouse x{mouse_qty}: ${mouse_total:.2f}")
print(f"Keyboard x{keyboard_qty}: ${keyboard_total:.2f}")
print("-" * 30)
print(f"Subtotal: ${subtotal:.2f}")
print(f"Tax (8%): ${tax:.2f}")
print("-" * 30)
print(f"TOTAL: ${total:.2f}")

⚖️ 2. Comparison Operators: Making Decisions

Comparison operators compare two values and return True or False — think of them like judges in a competition, evaluating and giving a verdict.

Equal To (==)

📌 What this code does: checks equality between numbers, variables, and strings — and shows that string comparison is case-sensitive and that different types are never equal.
# Basic equality check
print(5 == 5)      # Output: True
print(5 == 3)      # Output: False

# Comparing variables
age = 18
if age == 18:
    print("You just turned 18!")

# String comparison (case-sensitive!)
name = "Alice"
print(name == "Alice")   # Output: True
print(name == "alice")   # Output: False (different case!)

# Comparing different types
print(5 == "5")    # Output: False (int vs string)
❌ Common Mistake: = vs ==
# Single = is assignment
x = 5     # Assigns 5 to x

# Double == is comparison
x == 5    # Checks if x equals 5

# Wrong usage:
if x = 5:  # Error! Should be ==
    print("x is 5")

Not Equal To (!=)

📌 What this code does: checks inequality, validates a password attempt, and confirms a username field isn't left empty.
# Basic inequality check
print(5 != 3)      # Output: True
print(5 != 5)      # Output: False

# Practical example: Validation
password = input("Enter password: ")
if password != "secret123":
    print("Incorrect password!")
else:
    print("Access granted!")

# Check if not empty
username = input("Enter username: ")
if username != "":
    print(f"Welcome, {username}!")
else:
    print("Username cannot be empty!")

Greater Than (>) and Less Than (<)

📌 What this code does: compares numbers directly, checks age eligibility, and shows that Python can even compare strings alphabetically.
# Basic comparison
print(10 > 5)      # Output: True
print(5 > 10)      # Output: False
print(5 > 5)       # Output: False (not greater, equal)

# Practical example: Age verification
age = 25
if age > 18:
    print("You are an adult")

# Temperature check
temperature = 35
if temperature > 30:
    print("It's hot outside!")

# String comparison (alphabetical order)
print("banana" > "apple")   # Output: True (b comes after a)
# Basic comparison
print(5 < 10)      # Output: True
print(10 < 5)      # Output: False
print(5 < 5)       # Output: False

# Practical example: Grade check
score = 45
if score < 50:
    print("You need to improve")

# Price comparison
budget = 100
price = 149.99
if price < budget:
    print("Within budget!")
else:
    print("Too expensive!")

Greater Than or Equal (>=) and Less Than or Equal (<=)

📌 What this code does: shows that these operators count equal values as satisfying the condition, then applies them to a voting-age check and a passing-grade boundary.
# Basic comparison
print(10 >= 5)     # Output: True
print(5 >= 5)      # Output: True (equal counts!)
print(3 >= 5)      # Output: False

# Practical example: Minimum age requirement
age = 18
if age >= 18:
    print("Eligible to vote")

# Grade boundary
score = 60
if score >= 60:
    print("You passed!")
else:
    print("You failed")
# Basic comparison
print(5 <= 10)     # Output: True
print(5 <= 5)      # Output: True (equal counts!)
print(10 <= 5)     # Output: False

# Practical example: Speed limit
speed = 65
speed_limit = 70
if speed <= speed_limit:
    print("Driving safely")
else:
    print("Speeding!")

Comparison Operators Summary Table

Operator Name Example Result
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than5 > 3True
<Less than5 < 10True
>=Greater than or equal5 >= 5True
<=Less than or equal5 <= 10True

Chaining Comparisons

Python allows you to chain comparisons — a unique feature most other languages don't have!

📌 What this code does: checks if a value falls inside a range in one clean expression, then applies the same idea to a temperature-comfort check.
# Check if value is in range
age = 25
print(18 <= age <= 65)  # Output: True

# Without chaining (other languages)
print(age >= 18 and age <= 65)  # Same result, longer

# Multiple chains
score = 75
print(0 <= score <= 100)  # Valid score range

# Practical example: Temperature ranges
temp = 22
if 18 <= temp <= 24:
    print("Comfortable temperature")
elif temp < 18:
    print("Too cold")
else:
    print("Too hot")
✅ Chaining Benefits:
  • More readable than multiple conditions
  • Evaluates left to right
  • Stops at first False (short-circuit)
  • Cleaner than using 'and' operators

🔗 3. Logical Operators: Combining Conditions

Logical operators let you combine multiple conditions — think of them as the glue that connects decision rules.

AND Operator (and)

Returns True only if BOTH conditions are true.

📌 What this code does: requires every condition to be true simultaneously — validating login credentials, driving eligibility, and a passing score range.
# Basic AND
print(True and True)    # Output: True
print(True and False)   # Output: False
print(False and False)  # Output: False

# Practical example: Login validation
username = "alice"
password = "secret123"

if username == "alice" and password == "secret123":
    print("Login successful!")
else:
    print("Invalid credentials")

# Multiple conditions
age = 25
has_license = True
has_car = True

if age >= 18 and has_license and has_car:
    print("You can drive!")

# Range checking
score = 75
if score >= 60 and score <= 100:
    print("Valid passing score")
💡 AND Truth Table:
A      B      A and B
True   True   True
True   False  False
False  True   False
False  False  False
ALL must be True for result to be True!

OR Operator (or)

Returns True if AT LEAST ONE condition is true.

📌 What this code does: passes if any one condition is true — checking for weekend days, accepted payment methods, and admin-or-owner access.
# Basic OR
print(True or True)     # Output: True
print(True or False)    # Output: True
print(False or False)   # Output: False

# Practical example: Weekend check
day = "Saturday"
if day == "Saturday" or day == "Sunday":
    print("It's the weekend!")

# Multiple options
payment_method = "credit_card"
if payment_method == "cash" or payment_method == "credit_card" 
    or payment_method == "debit": print("Payment method accepted") # Emergency access is_admin = False is_owner = True if is_admin or is_owner: print("Access granted")
💡 OR Truth Table:
A      B      A or B
True   True   True
True   False  True
False  True   True
False  False  False
At least ONE must be True for result to be True!

NOT Operator (not)

Reverses the boolean value — True becomes False, False becomes True.

📌 What this code does: flips boolean values and conditions — checking "not logged in," "not weekend," an empty list being treated as false, and inverting an age check.
# Basic NOT
print(not True)    # Output: False
print(not False)   # Output: True

# Practical example: Check if NOT logged in
is_logged_in = False
if not is_logged_in:
    print("Please log in")

# Inverting conditions
is_weekend = False
if not is_weekend:
    print("It's a weekday")

# Check if list is NOT empty
items = []
if not items:  # Empty list is Falsy, not makes it True
    print("No items in cart")

# Combining with other operators
age = 15
if not (age >= 18):
    print("You are a minor")

Combining Logical Operators

📌 What this code does: combines and, or, and not into realistic multi-condition rules — a ticket discount policy and a content-moderation access check.
# Complex example: Ticket pricing
age = 25
is_student = True
is_senior = False

# Student or senior discount
if (age < 18 or is_student or is_senior) and age >= 5:
    print("Discounted ticket: $8")
elif age < 5:
    print("Free entry")
else:
    print("Regular ticket: $15")

# Access control
is_admin = False
is_moderator = True
is_banned = False

if (is_admin or is_moderator) and not is_banned:
    print("You can moderate content")
✅ Best Practices:
  • Use parentheses for clarity: (a and b) or c
  • not has highest precedence, then and, then or
  • Keep conditions simple and readable
  • Break complex logic into separate variables

Short-Circuit Evaluation

Python stops evaluating as soon as the result is known — this is called "short-circuiting."

📌 What this code does: proves Python skips evaluating the second condition once the outcome is already certain — and shows how this safely avoids crashing on a None value or a zero divisor.
# AND short-circuit
# If first is False, Python doesn't check the rest
result = False and print("This won't print")
print(result)  # Output: False

# OR short-circuit
# If first is True, Python doesn't check the rest
result = True or print("This won't print either")
print(result)  # Output: True

# Practical use: Avoid errors
user = None
# This won't crash because user is None (Falsy)
# Python doesn't evaluate user.name
name = user and user.name
print(name)  # Output: None

# Safe division
divisor = 0
result = divisor != 0 and (10 / divisor)
print(result)  # Output: False (doesn't attempt division)

📥 4. Assignment Operators: Efficient Updates

Assignment operators assign values to variables. The augmented versions provide shortcuts for common operations.

Simple Assignment (=)

📌 What this code does: assigns basic values, shows how one value can be assigned to several variables at once, and unpacks three values into three variables in a single line.
# Basic assignment
x = 10
name = "Alice"
is_active = True

# Multiple assignment
a = b = c = 0

# Unpacking assignment
x, y, z = 10, 20, 30
print(x, y, z)  # Output: 10 20 30

Add and Assign (+=)

📌 What this code does: compares the long way of adding-then-reassigning to the shortcut +=, then uses it to build up a game score across multiple events.
# Long way
score = 10
score = score + 5
print(score)  # Output: 15

# Short way
score = 10
score += 5  # Same as: score = score + 5
print(score)  # Output: 15

# Practical example: Game score
score = 0
print(f"Score: {score}")

score += 10   # Killed enemy
print(f"Score: {score}")

score += 50   # Completed level
print(f"Score: {score}")

score += 100  # Found treasure
print(f"Score: {score}")

# Output:
# Score: 0
# Score: 10
# Score: 60
# Score: 160

The Rest of the Augmented Assignment Operators

📌 What this code does: applies -= to simulate taking damage and reducing stock, *= to apply a points bonus and compound interest, /= to split a total evenly, //= to count full boxes, %= to isolate a last digit, and **= to cube a number — all using the shortcut form.
# Subtract and Assign (-=)
health = 100
health -= 20  # Took damage
print(f"Health: {health}")  # Output: Health: 80

stock = 50
sold = 12
stock -= sold
print(f"Remaining stock: {stock}")# Output: Remaining stock: 38

# Multiply and Assign (*=)
points = 10
points *= 2  # Double points bonus
print(points)  # Output: 20

balance = 1000
interest_rate = 1.05
balance *= interest_rate
print(f"New balance: ${balance}") # Output: New balance: $1050.0

# Divide and Assign (/=)
total = 100
people = 4
total /= people  # Split equally
print(f"Each gets: ${total}")  # Output: Each gets: $25.0

# Floor Divide and Assign (//=)
items = 47
box_size = 12
items //= box_size  # How many full boxes?
print(f"Full boxes: {items}")  # Output: Full boxes: 3

# Modulus and Assign (%=)
number = 47
number %= 10  # Get last digit
print(number)  # Output: 7

# Exponent and Assign (**=)
base = 2
base **= 3  # 2³
print(base)  # Output: 8

Assignment Operators Summary Table

Operator Example Equivalent to
=x = 5x = 5
+=x += 5x = x + 5
-=x -= 5x = x - 5
*=x *= 5x = x * 5
/=x /= 5x = x / 5
//=x //= 5x = x // 5
%=x %= 5x = x % 5
**=x **= 5x = x ** 5
✅ Why Use Augmented Assignment?
  • More concise and readable
  • Less typing, fewer errors
  • Industry standard practice
  • Slightly more efficient (in some cases)

🪪 5. Identity Operators: Checking Object Identity

Identity operators check if two variables point to the same object in memory, not just whether they have the same value.

is Operator

📌 What this code does: creates two lists with identical contents but different identities, then a third variable pointing to the same object as the first — showing the difference between "equal values" and "the same object."
# Checking identity
x = [1, 2, 3]
y = [1, 2, 3]
z = x

print(x == y)   # Output: True (same values)
print(x is y)   # Output: False (different objects)
print(x is z)   # Output: True (same object)

# Visualizing:
# x ---> [1, 2, 3] (Object 1)
# y ---> [1, 2, 3] (Object 2) - different object, same values
# z ---> [1, 2, 3] (Object 1) - same object as x
💡 is vs ==:
  • == compares VALUES (are they equal?)
  • is compares IDENTITY (are they the same object?)
  • Use is for None, True, False
  • Use == for everything else

Checking for None

📌 What this code does: shows the recommended way to check for None (with is) and the "not None" check used to confirm a value actually exists.
# Correct way to check for None
value = None

if value is None:
    print("Value is None")

# Not recommended (but works)
if value == None:
    print("Value is None")

# Checking if NOT None
user = {"name": "Alice"}
if user is not None:
    print("User exists")

is not Operator

📌 What this code does: confirms two lists are different objects, then uses is not None to greet a logged-in user only if one actually exists.
# Basic usage
x = [1, 2, 3]
y = [1, 2, 3]

print(x is not y)  # Output: True (different objects)

# Practical example
current_user = None

if current_user is not None:
    print(f"Welcome back, {current_user}!")
else:
    print("Please log in")

Small Integer Caching

Python caches small integers (-5 to 256) for performance.

📌 What this code does: reveals a Python implementation detail — small integers and some strings are cached and reused, so is can behave unexpectedly compared to larger numbers.
# Small integers
a = 10
b = 10
print(a is b)  # Output: True (same cached object!)

# Large integers
a = 1000
b = 1000
print(a is b)  # Output: False (different objects)

# Strings (sometimes cached)
a = "hello"
b = "hello"
print(a is b)  # Output: True (interned strings)
❌ Common Mistake:
# Don't use 'is' to compare values!
x = 1000
y = 1000
if x is y:  # Wrong! Use ==
    print("Equal")

# Correct:
if x == y:
    print("Equal")
Never use is to compare numbers or strings (except None, True, False).

🔎 6. Membership Operators: Checking Membership

Membership operators check if a value exists in a sequence (strings, lists, tuples, or sets).

in Operator

📌 What this code does: checks whether a substring, list item, or tuple value exists, and clarifies that checking a dictionary with in looks at its keys, not its values.
# Check in string
text = "Hello, World!"
print("Hello" in text)   # Output: True
print("Python" in text)  # Output: False

# Check in list
fruits = ["apple", "banana", "orange"]
print("apple" in fruits)    # Output: True
print("grape" in fruits)    # Output: False

# Check in tuple
numbers = (1, 2, 3, 4, 5)
print(3 in numbers)  # Output: True
print(10 in numbers) # Output: False

# Check dictionary keys (not values!)
person = {"name": "Alice", "age": 25}
print("name" in person)   # Output: True (key exists)
print("Alice" in person)  # Output: False (value, not key!)

Practical Examples with in

📌 What this code does: uses in for real validation tasks — checking an email has an "@" and a ".", detecting vowels, validating a menu selection, and scanning a message for banned words.
# Email validation
email = "user@example.com"
if "@" in email and "." in email:
    print("Valid email format")

# Vowel checker
letter = "a"
if letter in "aeiou":
    print(f"{letter} is a vowel")

# Menu selection
valid_choices = ["A", "B", "C", "D"]
user_choice = input("Select (A/B/C/D): ").upper()
if user_choice in valid_choices:
    print(f"You selected: {user_choice}")
else:
    print("Invalid choice!")

# Word filter
banned_words = ["spam", "hack", "cheat"]
message = input("Enter message: ").lower()
if any(word in message for word in banned_words):
    print("Message contains banned words!")

not in Operator

📌 What this code does: checks the absence of a value — denying access to a non-whitelisted user and preventing duplicate items from being added to a shopping cart.
# Check NOT in string
text = "Python Programming"
print("Java" not in text)  # Output: True

# Check NOT in list
allowed_users = ["alice", "bob", "charlie"]
user = "david"
if user not in allowed_users:
    print("Access denied!")

# Practical example: Unique items
shopping_cart = ["apple", "banana", "orange"]
new_item = "grape"
if new_item not in shopping_cart:
    shopping_cart.append(new_item)
    print(f"Added {new_item} to cart")
else:
    print(f"{new_item} already in cart")

Case-Sensitive Membership

📌 What this code does: shows that in is case-sensitive by default, then fixes that by lowercasing both sides before comparing.
# Membership is case-sensitive!
text = "Hello, World!"
print("hello" in text)  # Output: False (lowercase)
print("Hello" in text)  # Output: True (exact case)

# Case-insensitive check
text = "Hello, World!"
search = "hello"
if search.lower() in text.lower():
    print("Found (case-insensitive)")

🧮 7. Bitwise Operators: Low-Level Operations

Bitwise operators work on the binary representation of numbers. These are more advanced but useful for certain specialized tasks.

💡 When Are Bitwise Operators Used?
  • Low-level programming (device drivers, embedded systems)
  • Performance-critical operations
  • Flags and permissions (file permissions, user roles)
  • Cryptography and hashing
  • Network programming
Beginners can skip this section initially and return later!

Understanding Binary

📌 What this code does: converts decimal numbers into their binary text representation using Python's built-in bin() function.
# Decimal to binary conversion
print(bin(5))   # Output: 0b101 (binary representation)
print(bin(10))  # Output: 0b1010

# Binary breakdown:
# 5 in binary = 101 = (1×4) + (0×2) + (1×1) = 4+0+1 = 5
# 10 in binary = 1010 = (1×8) + (0×4) + (1×2) + 
                (0×1) = 8+0+2+0 = 10

Bitwise AND (&), OR (|), and XOR (^)

📌 What this code does: compares numbers bit-by-bit using AND, OR, and XOR, uses AND to quickly detect even numbers, and uses XOR to swap two variables without a temporary variable.
# Bitwise AND — 1 only if both bits are 1
result = 5 & 3
print(result)  # Output: 1
#   5 = 101
#   3 = 011
# --------- (AND)
#   1 = 001

# Practical use: Check if number is even
number = 42
if number & 1 == 0:
    print("Even")  # If last bit is 0, number is even
else:
    print("Odd")

# Bitwise OR — 1 if at least one bit is 1
result = 5 | 3
print(result)  # Output: 7
#   5 = 101
#   3 = 011
# --------- (OR)
#   7 = 111

# Bitwise XOR — 1 if bits are different
result = 5 ^ 3
print(result)  # Output: 6
#   5 = 101
#   3 = 011
# --------- (XOR)
#   6 = 110

# Practical use: Swap without temp variable
a = 10
b = 20
a = a ^ b
b = a ^ b
a = a ^ b
print(f"a = {a}, b = {b}")  # Output: a = 20, b = 10

Bitwise NOT (~), Left Shift (<<), and Right Shift (>>)

📌 What this code does: inverts all bits of a number, then shifts bits left (a fast way to multiply by powers of 2) and right (a fast way to divide by powers of 2).
# Bitwise NOT — inverts all bits, returns -(n+1)
result = ~5
print(result)  # Output: -6

# Left shift — equivalent to multiplying by 2^n
result = 5 << 1
print(result)  # Output: 10
#   5 = 101
# 5<<1 1010="10" 1="" 20="" 2="" 4="20" 5="" by="" dividing="" equivalent="" left="" n="" output:="" position="" print="" result="10" right="" shift="" shifted="" to="">> 1
print(result)  # Output: 5
#   10 = 1010
# 10>>1 = 101 = 5 (shifted right by 1 position)

result = 20 >> 2  # 20 / 2² = 20 / 4 = 5
print(result)  # Output: 5

Bitwise Operators Summary

Operator Name Example Result
&AND5 & 31
|OR5 | 37
^XOR5 ^ 36
~NOT~5-6
<<Left Shift5 << 110
>>Right Shift10 >> 15

🎯 8. Operator Precedence: Order of Operations

When you combine multiple operators, Python follows specific rules to determine which operation happens first. Remember PEMDAS from math class? Python has similar rules.

Precedence Hierarchy (Highest to Lowest)

  1. Parentheses: ()
  2. Exponentiation: **
  3. Unary operators: +x, -x, ~x
  4. Multiplication, Division, Modulus: *, /, //, %
  5. Addition, Subtraction: +, -
  6. Bitwise shifts: <<, >>
  7. Bitwise AND: &
  8. Bitwise XOR: ^
  9. Bitwise OR: |
  10. Comparisons: ==, !=, >, <, >=, <=, is, in
  11. Boolean NOT: not
  12. Boolean AND: and
  13. Boolean OR: or

Precedence Examples

📌 What this code does: walks through four expressions step-by-step to show exactly which operation Python performs first — multiplication before addition, exponents before addition, left-to-right for equal-precedence operators, and a fully mixed expression.
# Example 1: Arithmetic
result = 10 + 5 * 2
print(result)  # Output: 20 (not 30!)
# Explanation: 5 * 2 happens first = 10, then 10 + 10 = 20

# With parentheses
result = (10 + 5) * 2
print(result)  # Output: 30
# Explanation: (10 + 5) happens first = 15, then 15 * 2 = 30

# Example 2: Exponentiation
result = 2 + 3 ** 2
print(result)  # Output: 11 (not 25!)
# Explanation: 3 ** 2 = 9, then 2 + 9 = 11

# Example 3: Division and multiplication (left to right)
result = 20 / 4 * 2
print(result)  # Output: 10.0
# Explanation: 20 / 4 = 5.0, then 5.0 * 2 = 10.0

# Example 4: Mixed operators
result = 10 + 5 * 2 ** 2 - 3
# Step by step:
# 2 ** 2 = 4 (exponentiation first)
# 5 * 4 = 20 (multiplication)
# 10 + 20 = 30 (addition, left to right)
# 30 - 3 = 27 (subtraction)
print(result)  # Output: 27

Comparison and Logical Precedence

📌 What this code does: shows that comparisons resolve before and, and and resolves before or, then reworks the same logic with explicit parentheses for clarity.
# Comparisons before 'and'
result = 5 > 3 and 10 < 20
# Evaluated as: (5 > 3) and (10 < 20) = True and True = True
print(result)  # Output: True

# 'and' before 'or'
result = True or False and False
# Evaluated as: True or (False and False) = True or False = True
print(result)  # Output: True

# With parentheses (clearer)
result = (True or False) and False
# Evaluated as: True and False = False
print(result)  # Output: False
✅ Best Practice: Use Parentheses!
Even if you know the precedence rules, use parentheses for clarity.
# Hard to read
result = x > 5 and y < 10 or z == 0

# Much clearer
result = (x > 5 and y < 10) or (z == 0)
Your future self (and teammates) will thank you!

Associativity

When operators have the same precedence, associativity determines evaluation order.

📌 What this code does: shows that most operators evaluate left-to-right, but exponentiation is the one major exception — it evaluates right-to-left.
# Most operators are left-to-right
result = 10 - 5 - 2
# Evaluated as: (10 - 5) - 2 = 5 - 2 = 3
print(result)  # Output: 3

# Exponentiation is right-to-left
result = 2 ** 3 ** 2
# Evaluated as: 2 ** (3 ** 2) = 2 ** 9 = 512
print(result)  # Output: 512

# Not the same as:
result = (2 ** 3) ** 2
print(result)  # Output: 64

🌍 9. Real-World Examples: Putting It All Together

Example 1: Grade Calculator

📌 What this code does: collects three scores, computes a weighted final grade using arithmetic operators, assigns a letter grade with comparison chains, and checks honors eligibility with combined logical operators.
print("=== Grade Calculator ===\n")

midterm = float(input("Midterm score (0-100): "))
final = float(input("Final score (0-100): "))
assignments = float(input("Assignment average (0-100): "))

# Midterm: 30%, Final: 40%, Assignments: 30%
total = (midterm * 0.3) + (final * 0.4) + (assignments * 0.3)

print(f"\nFinal Grade: {total:.2f}%")

if total >= 90:
    letter = "A"
    status = "Excellent!"
elif total >= 80:
    letter = "B"
    status = "Great job!"
elif total >= 70:
    letter = "C"
    status = "Good work!"
elif total >= 60:
    letter = "D"
    status = "Passed, but needs improvement"
else:
    letter = "F"
    status = "Failed - please retake the course"

print(f"Letter Grade: {letter}")
print(f"Status: {status}")

is_honors = total >= 85 and midterm >= 80 and final >= 80
if is_honors:
    print("\n🎉 Congratulations! You qualify for honors!")

Example 2: Shopping Discount Calculator

📌 What this code does: stacks multiple discounts using +=, applies them as a percentage using arithmetic operators, then adds tax and prints a full breakdown.
print("=== Shopping Discount Calculator ===\n")

subtotal = float(input("Enter subtotal: $"))
is_member = input("Are you a member? (yes/no): ")
            .lower() == "yes" has_coupon = input("Do you have a coupon? (yes/no): ")
            .lower() == "yes" discount_percent = 0 if is_member: discount_percent += 10 print("✓ Member discount: 10%") if has_coupon: discount_percent += 5 print("✓ Coupon discount: 5%") if subtotal >= 100: discount_percent += 15 print("✓ Bulk purchase discount: 15%") discount_amount = subtotal * (discount_percent / 100) total = subtotal - discount_amount tax = total * 0.08 final_total = total + tax print(f"\nSubtotal: ${subtotal:.2f}") print(f"Total Discount ({discount_percent}%):-${discount_amount:.2f}") print(f"After Discount: ${total:.2f}") print(f"Tax (8%): ${tax:.2f}") print(f"Final Total: ${final_total:.2f}") if discount_percent > 0: print(f"\n💰 You saved ${discount_amount:.2f}!")

Example 3: Password Strength Validator

📌 What this code does: checks a password against five criteria using comparison and membership operators, sums the True/False results into a strength score, and reports the outcome with a warning for common weak patterns.
print("=== Password Strength Validator ===\n")

password = input("Enter password: ")

min_length = len(password) >= 8
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password)
has_special = any(c in "!@#$%^&*()_+-=[]{}|;:,
                    .<>?" for c in password) strength_score = sum([min_length, has_upper,
                has_lower, has_digit, has_special]) print("\nPassword Requirements:") print(f"{'✓' if min_length else '✗'}
            At least 8 characters") print(f"{'✓' if has_upper else '✗'}
            At least one uppercase letter") print(f"{'✓' if has_lower else '✗'}
            At least one lowercase letter") print(f"{'✓' if has_digit else '✗'}
            At least one digit") print(f"{'✓' if has_special else '✗'}
            At least one special character") if strength_score == 5: strength = "Very Strong 🔒" elif strength_score >= 4: strength = "Strong 🔐" elif strength_score >= 3: strength = "Moderate ⚠️" else: strength = "Weak ❌" print(f"\nPassword Strength: {strength}") if "password" in password.lower() or "123456" in password: print("⚠️ Warning: Password contains common patterns!") if len(password) >= 12 and strength_score == 5: print("✓ Excellent password!")

Example 4: Time Calculator

📌 What this code does: converts a raw number of seconds into hours, minutes, and seconds using floor division and modulus together, then formats the result a couple of different ways.
print("=== Time Calculator ===\n")

total_seconds = int(input("Enter total seconds: "))

hours = total_seconds // 3600
remaining = total_seconds % 3600
minutes = remaining // 60
seconds = remaining % 60

print(f"\n{total_seconds} seconds equals:")
print(f"{hours} hours, {minutes} minutes, {seconds} seconds")

if hours > 0:
    print(f"Or: {hours}h {minutes}m {seconds}s")
elif minutes > 0:
    print(f"Or: {minutes}m {seconds}s")
else:
    print(f"Or: {seconds}s")

if total_seconds >= 86400:
    days = total_seconds // 86400
    print(f"\nThat's {days} day(s)!")

if total_seconds == 3600:
    print("\nThat's exactly one hour!")

# Example usage:
# Input: 7384
# Output:
# 7384 seconds equals:
# 2 hours, 3 minutes, 4 seconds
# Or: 2h 3m 4s

🚧 10. Common Pitfalls and How to Avoid Them

❌ Pitfall 1: Integer Division Surprises
# In Python 3, / always returns float
result = 10 / 2
print(result)  # Output: 5.0 (not 5!)

# Use // for integer division
result = 10 // 2
print(result)  # Output: 5
❌ Pitfall 2: Assignment vs Comparison
# Wrong - assignment in condition
if x = 5:  # SyntaxError!
    print("x is 5")

# Correct - comparison
if x == 5:
    print("x is 5")
❌ Pitfall 3: Floating Point Precision
# Direct comparison can fail
result = 0.1 + 0.2
print(result == 0.3)  # Output: False!

# Use approximate comparison
print(abs(result - 0.3) < 0.0001)  # Output: True

# Or use decimal module for precise calculations
from decimal import Decimal
result = Decimal('0.1') + Decimal('0.2')
print(result == Decimal('0.3'))  # Output: True
❌ Pitfall 4: Operator Precedence Confusion
# Unclear precedence
result = 5 + 3 * 2
# Is it (5+3)*2=16 or 5+(3*2)=11?
# Answer: 11 (multiplication first)

# Better: use parentheses
result = 5 + (3 * 2)  # Clear!
result = (5 + 3) * 2  # Also clear!
❌ Pitfall 5: String Concatenation Type Errors
# Wrong - mixing types
age = 25
message = "I am " + age + " years old"  # TypeError!

# Correct - convert to string
message = "I am " + str(age) + " years old"

# Better - use f-strings
message = f"I am {age} years old"

✍️ 11. Practice Exercises

✅ Exercise 1: Temperature Converter
Create a program that converts Celsius to Fahrenheit and vice versa. Formula: F = (C × 9/5) + 32

Bonus: Add Kelvin conversion (K = C + 273.15)
✅ Exercise 2: Leap Year Checker
Write a program that determines if a year is a leap year.
Rules:
  • Divisible by 4 → leap year
  • UNLESS divisible by 100 → not a leap year
  • UNLESS divisible by 400 → leap year
Hint: Use modulus and logical operators
✅ Exercise 3: BMI Calculator
Calculate Body Mass Index and categorize the result.
Formula: BMI = weight (kg) / height² (m)
Categories:
  • < 18.5: Underweight
  • 18.5 - 24.9: Normal
  • 25 - 29.9: Overweight
  • ≥ 30: Obese
✅ Exercise 4: Even or Odd Analyzer
Create a program that:
  • Takes a number as input
  • Checks if it's even or odd
  • Checks if it's positive or negative
  • Checks if it's divisible by 3, 5, or both
✅ Exercise 5: Rock, Paper, Scissors
Build a simple game where:
  • Two players enter their choice
  • Program determines the winner using comparison operators
  • Rock beats Scissors, Scissors beats Paper, Paper beats Rock

📚 12. Operator Cheat Sheet

📚 Quick Reference Guide

Arithmetic:

+    Addition          5 + 3 = 8
-    Subtraction       5 - 3 = 2
*    Multiplication    5 * 3 = 15
/    Division          5 / 2 = 2.5
//   Floor Division    5 // 2 = 2
%    Modulus           5 % 2 = 1
**   Exponentiation    5 ** 2 = 25

Comparison:

==   Equal to              5 == 5 → True
!=   Not equal to          5 != 3 → True
>    Greater than          5 > 3 → True
<    Less than             5 < 10 → True
>=   Greater or equal      5 >= 5 → True
<=   Less or equal         5 <= 10 → True

Logical:

and  Both True            True and True → True
or   At least one True    True or False → True
not  Reverse boolean      not True → False

Assignment:

=    Assign               x = 5
+=   Add and assign       x += 3  (x = x + 3)
-=   Subtract and assign  x -= 3  (x = x - 3)
*=   Multiply and assign  x *= 3  (x = x * 3)
/=   Divide and assign    x /= 3  (x = x / 3)

Identity & Membership:

is       Same object       x is y
is not   Different object  x is not y
in       In sequence       'a' in 'apple'
not in   Not in sequence   'x' not in 'apple'

❓ Frequently Asked Questions

What's the difference between / and // in Python?

/ always returns a float (e.g. 10 / 2 is 5.0), while // performs floor division and rounds down to the nearest whole number (e.g. 10 // 3 is 3).

What's the difference between = and ==?

A single = assigns a value to a variable. A double == compares two values and returns True or False. Using = inside an if statement is a syntax error in Python.

When should I use "is" instead of "=="?

Use is only for identity checks, most commonly x is None. Use == for comparing values like numbers, strings, or list contents.

What does short-circuit evaluation mean?

Python stops evaluating a logical expression as soon as the outcome is certain — for example, in False and x(), x() is never called because the result is already known to be False.

Why does 0.1 + 0.2 not equal 0.3 in Python?

This is a floating-point precision limitation shared by nearly all programming languages, not a Python bug. Use an approximate comparison (abs(a - b) < 0.0001) or the decimal module when exact precision matters.

Do I need to learn bitwise operators as a beginner?

Not right away. Bitwise operators are mainly used in low-level programming, performance-critical code, and permission flags. It's fine to skip this section initially and come back once you need it.

📝 Key Takeaways

  1. Operators are actions — they tell Python what to do with data
  2. Use the right operator — == for comparison, = for assignment
  3. Precedence matters — use parentheses when in doubt
  4. Augmented assignment is cleaner — use += instead of x = x +
  5. is vs == — use is for None, == for values
  6. Short-circuit evaluation — Python stops when the result is known
  7. Floor division vs division — // gives int-like results, / gives float
  8. Modulus is powerful — great for cycling and divisibility checks
✅ Pro Tips for Mastery:
  • Practice operators daily — even 15 minutes helps
  • Use Python's interactive shell to experiment
  • When unsure about precedence, add parentheses
  • Read error messages carefully — they tell you what's wrong
  • Use f-strings for cleaner string formatting
  • Write code that's readable, not just functional
  • Comment complex operator combinations
  • Build small projects to apply what you learned

Keep coding, keep experimenting, keep learning! 🐍✨

Comments