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?
- 1. Arithmetic Operators
- 2. Comparison Operators
- 3. Logical Operators
- 4. Assignment Operators
- 5. Identity Operators
- 6. Membership Operators
- 7. Bitwise Operators
- 8. Operator Precedence
- 9. Real-World Examples
- 10. Common Pitfalls
- 11. Practice Exercises
- 12. Operator Cheat Sheet
- FAQ
- Key Takeaways
🔧 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.
# 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:
- Arithmetic Operators — math operations (
+,-,*,/) - Comparison Operators — compare values (
==,!=,>,<) - Logical Operators — combine conditions (
and,or,not) - Assignment Operators — assign values (
=,+=,-=) - Bitwise Operators — binary operations (
&,|,^) - Identity Operators — check object identity (
is,is not) - 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 (+)
# 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
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 (-)
# 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 (*)
# 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
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.
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
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.
# 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.
# 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
- 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.
# 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 |
|---|---|---|---|
+ | Addition | 10 + 5 | 15 |
- | Subtraction | 10 - 5 | 5 |
* | Multiplication | 10 * 5 | 50 |
/ | Division | 10 / 3 | 3.333... |
// | Floor Division | 10 // 3 | 3 |
% | Modulus | 10 % 3 | 1 |
** | Exponentiation | 2 ** 3 | 8 |
Real-World Example: Shopping Cart Calculator
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 (==)
# 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)
# 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 (!=)
# 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 (<)
# 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 (<=)
# 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 to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 5 > 3 | True |
< | Less than | 5 < 10 | True |
>= | Greater than or equal | 5 >= 5 | True |
<= | Less than or equal | 5 <= 10 | True |
Chaining Comparisons
Python allows you to chain comparisons — a unique feature most other languages don't have!
# 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")
- 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.
# 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")
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.
# 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")
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.
# 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
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")
- Use parentheses for clarity:
(a and b) or c nothas highest precedence, thenand, thenor- 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."
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 (=)
# 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 (+=)
+=, 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
-= 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 = 5 | x = 5 |
+= | x += 5 | x = x + 5 |
-= | x -= 5 | x = x - 5 |
*= | x *= 5 | x = x * 5 |
/= | x /= 5 | x = x / 5 |
//= | x //= 5 | x = x // 5 |
%= | x %= 5 | x = x % 5 |
**= | x **= 5 | x = x ** 5 |
- 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
# 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
==compares VALUES (are they equal?)iscompares IDENTITY (are they the same object?)- Use
isfor None, True, False - Use
==for everything else
Checking for None
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
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.
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)
# 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
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
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
# 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
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.
- Low-level programming (device drivers, embedded systems)
- Performance-critical operations
- Flags and permissions (file permissions, user roles)
- Cryptography and hashing
- Network programming
Understanding Binary
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 (^)
# 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 (>>)
# 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: 51>
Bitwise Operators Summary
| 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 | 10 >> 1 | 5 |
🎯 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)
- Parentheses:
() - Exponentiation:
** - Unary operators:
+x,-x,~x - Multiplication, Division, Modulus:
*,/,//,% - Addition, Subtraction:
+,- - Bitwise shifts:
<<,>> - Bitwise AND:
& - Bitwise XOR:
^ - Bitwise OR:
| - Comparisons:
==,!=,>,<,>=,<=,is,in - Boolean NOT:
not - Boolean AND:
and - Boolean OR:
or
Precedence Examples
# 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
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
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.
# 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
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
+=, 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
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
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
# 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
# Wrong - assignment in condition
if x = 5: # SyntaxError!
print("x is 5")
# Correct - comparison
if x == 5:
print("x is 5")
# 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
# 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!
# 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
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)
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
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
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
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
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
/ 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).
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.
Use is only for identity checks, most commonly x is None. Use
== for comparing values like numbers, strings, or list contents.
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.
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.
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
- Operators are actions — they tell Python what to do with data
- Use the right operator —
==for comparison,=for assignment - Precedence matters — use parentheses when in doubt
- Augmented assignment is cleaner — use
+=instead ofx = x + - is vs == — use
isfor None,==for values - Short-circuit evaluation — Python stops when the result is known
- Floor division vs division —
//gives int-like results,/gives float - Modulus is powerful — great for cycling and divisibility checks
- 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
Post a Comment