- Master arithmetic operators for calculations
- Understand comparison operators for making decisions
- Use logical operators to combine conditions
- Learn assignment operators for shorthand operations
Operators and Expressions
If variables are the ingredients in your programming recipe, operators are the kitchen tools that let you work with them. Just like a chef uses knives to cut, whisks to mix, and spoons to measure, programmers use operators to calculate, compare, and combine data.
Operators are symbols that tell Python to perform specific operations. Whether you're calculating a shopping total, checking if a user is old enough to vote, or combining search conditions – operators make it all possible.
Arithmetic Operators – Your Math Toolkit
Arithmetic operators perform mathematical calculations. They work like a calculator, but with superpowers!
The Essential Seven
Arithmetic Operators
+ Addition 10 + 3 = 13
- Subtraction 10 - 3 = 7
* Multiplication 10 * 3 = 30
/ Division 10 / 3 = 3.333...
// Floor Division 10 // 3 = 3
% Modulo 10 % 3 = 1
** Exponentiation 10 ** 3 = 1000
Real-World Analogies
| Operator | Like in Real Life... |
|---|---|
+ Addition |
Adding items to a shopping cart |
- Subtraction |
Spending money from your wallet |
* Multiplication |
Calculating total for 5 items at $10 each |
/ Division |
Splitting a bill among friends |
// Floor Division |
How many complete groups of 4 from 15 people? |
% Modulo |
How many people left over after making groups? |
** Power |
Compound interest, exponential growth |
Division Deep Dive
Let's clarify the three types of division-related operations:
# Regular division (always returns float)
pizza_slices = 8
people = 3
each_person = pizza_slices / people # 2.666...
# Floor division (rounds down to whole number)
complete_slices = pizza_slices // people # 2 slices each
# Modulo (remainder after division)
leftover = pizza_slices % people # 2 slices left
Think of it like this: You have 8 pizzas and 3 friends. Each gets 2 complete pizzas (//), and 2 pizzas remain (%).
The Power Operator
# Square (to the power of 2)
side = 5
area = side ** 2 # 25
# Cube (to the power of 3)
edge = 3
volume = edge ** 3 # 27
# Square root (power of 0.5)
number = 16
root = number ** 0.5 # 4.0
String Operators – Working with Text
Operators aren't just for numbers! Some work beautifully with strings.
Concatenation (+)
first_name = "Alice"
last_name = "Smith"
full_name = first_name + " " + last_name # "Alice Smith"
# Building messages
greeting = "Hello, " + full_name + "!" # "Hello, Alice Smith!"
Repetition (*)
# Create patterns
line = "-" * 30 # "------------------------------"
border = "=" * 20 # "===================="
# Fun with text
echo = "Hello! " * 3 # "Hello! Hello! Hello! "
# Building visual elements
print("*" * 10)
print("*" + " " * 8 + "*")
print("*" * 10)
# Output:
# **********
# * *
# **********
Comparison Operators – Making Decisions
Comparison operators compare two values and return True or False. They're essential for making decisions in your code.
The Comparison Family
Comparison Operators
== Equal to 5 == 5 → True
!= Not equal to 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
Real-World Examples
# Age verification
age = 20
can_vote = age >= 18 # True
is_teenager = age < 20 # False
# Price comparison
price = 49.99
budget = 50.00
can_afford = price <= budget # True
# Password check
entered = "secret123"
correct = "secret123"
is_correct = entered == correct # True
Comparing Strings
Strings are compared alphabetically (lexicographically):
print("apple" < "banana") # True (a comes before b)
print("Apple" < "apple") # True (uppercase A < lowercase a)
print("cat" == "cat") # True (exact match)
print("cat" == "Cat") # False (case matters!)
Common Mistake: = vs ==
x = 5 # Assignment: "x gets the value 5"
x == 5 # Comparison: "is x equal to 5?" → True
# This is a VERY common beginner mistake!
# if x = 5: # SyntaxError! Use == for comparison
# if x == 5: # Correct!
Logical Operators – Combining Conditions
Logical operators combine multiple conditions. Think of them as connecting words: "and", "or", "not".
The Logic Trio
Logical Operators
and Both conditions must be True
or At least one condition must be True
not Reverses the condition (True→False, False→True)
Understanding with Truth Tables
AND - Both must be True:
| A | B | A and B |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
OR - At least one True:
| A | B | A or B |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
Real-World Analogies
AND is like a strict door:
"You need a ticket AND an ID to enter" – missing either, you can't enter.
OR is like flexible payment:
"You can pay with cash OR card" – either works!
NOT is like an opposite:
"Not closed" means "open"
Practical Examples
# AND: All conditions must be true
age = 25
has_license = True
can_rent_car = age >= 21 and has_license # True
# OR: At least one condition must be true
is_weekend = True
is_holiday = False
is_day_off = is_weekend or is_holiday # True
# NOT: Reverses the condition
is_raining = False
go_for_walk = not is_raining # True
# Complex combinations
temperature = 25
is_sunny = True
go_to_beach = temperature > 20 and is_sunny and not is_raining # True
Assignment Operators – Shorthand Magic
Assignment operators provide shortcuts for common operations.
The Assignment Family
Assignment Operators
= Simple assignment x = 5
+= Add and assign x += 3 (same as x = x + 3)
-= Subtract and assign x -= 3 (same as x = x - 3)
*= Multiply and assign x *= 3 (same as x = x * 3)
/= Divide and assign x /= 3 (same as x = x / 3)
//= Floor divide assign x //= 3 (same as x = x // 3)
%= Modulo and assign x %= 3 (same as x = x % 3)
**= Power and assign x **= 3 (same as x = x ** 3)
Before and After
# Without shorthand
score = 100
score = score + 10 # Add 10 points
score = score - 5 # Subtract 5 points
score = score * 2 # Double the score
# With shorthand (cleaner!)
score = 100
score += 10 # Add 10 points → 110
score -= 5 # Subtract 5 → 105
score *= 2 # Double → 210
Game Score Example
player_score = 0
# Player actions
player_score += 100 # Collected coin: +100
player_score += 50 # Defeated enemy: +50
player_score -= 25 # Took damage: -25
player_score *= 2 # Bonus level: double!
print(f"Final Score: {player_score}") # 250
Operator Precedence – Order Matters!
Just like in math class, Python follows an order of operations:
Operator Precedence (Highest to Lowest)
() Parentheses (always first!)
** Exponentiation
*, /, //, % Multiplication, Division, Modulo
+, - Addition, Subtraction
<, <=, >, >=, ==, != Comparisons
not Logical NOT
and Logical AND
or Logical OR
Examples That Show Why This Matters
# Without understanding precedence
result = 5 + 3 * 2 # Is it 16 or 11?
print(result) # 11 (multiplication first!)
# Use parentheses to be clear
result = (5 + 3) * 2 # Now it's 16
print(result)
# Complex example
x = 10
y = 5
z = 3
result = x + y * z # 10 + 15 = 25 (not 45!)
result = (x + y) * z # 15 * 3 = 45
Pro Tip: When in doubt, use parentheses! They make your intentions clear and prevent bugs.
Practical Example: Shopping Calculator
Let's use all our operators in a realistic scenario:
# Shopping cart calculation
item_price = 29.99
quantity = 3
discount_percent = 15
tax_rate = 0.08
# Calculate subtotal
subtotal = item_price * quantity # 89.97
# Apply discount
discount_amount = subtotal * (discount_percent / 100)
after_discount = subtotal - discount_amount # 76.47
# Add tax
tax_amount = after_discount * tax_rate
total = after_discount + tax_amount # 82.59
# Display receipt
print("=" * 35)
print(" SHOPPING RECEIPT")
print("=" * 35)
print(f"Item Price: ${item_price:.2f}")
print(f"Quantity: {quantity}")
print(f"Subtotal: ${subtotal:.2f}")
print(f"Discount ({discount_percent}%): -${discount_amount:.2f}")
print(f"After Discount: ${after_discount:.2f}")
print(f"Tax (8%): +${tax_amount:.2f}")
print("-" * 35)
print(f"TOTAL: ${total:.2f}")
print("=" * 35)
# Check if customer can afford it
wallet = 100.00
can_afford = wallet >= total # True
Key Takeaways
Remember These Points
ARITHMETIC: +, -, *, /, //, %, **
• / always returns float, // rounds down
• % gives remainder, ** is for powers
COMPARISON: ==, !=, <, >, <=, >=
• Return True or False
• == compares, = assigns (don't mix them!)
LOGICAL: and, or, not
• and: both must be True
• or: at least one True
• not: reverses the value
ASSIGNMENT: =, +=, -=, *=, /=
• x += 5 is shorthand for x = x + 5
PRECEDENCE: Use parentheses when in doubt!
What's Next?
Excellent work! You now have the tools to perform calculations, make comparisons, and combine conditions. In the next lesson, we'll learn about type conversion – how to transform data from one type to another when needed.
