Master arithmetic, comparison, logical, and assignment operators
Imagine you're building a shopping app. A customer adds items to their cart, and you need to calculate the total price, check if they qualify for a discount, and verify their payment is sufficient. Every single one of these actions requires operators. You'll compare values, perform math, and combine conditions constantly in your Python journey—and this tutorial will show you exactly how.
Operators are special symbols in Python that perform operations on values and variables. Think of them as the verbs of your code—they're the action words that make things happen. Just like in English where verbs connect subjects and objects ("The cat chases the mouse"), operators connect your data and make it do something useful.
An operator is a symbol that tells Python to perform a specific operation. For example, the + symbol tells Python to add two numbers together. The > symbol tells Python to check if one value is greater than another. Every operator has a specific job, and combining them is how you build logic into your programs.
Python operators fall into three major categories:
+, -, *, /, //, %, **)==, !=, >, <, >=, <=)and, or, not)There's also a fourth category—assignment operators (=, +=, -=)—which help you store and update values efficiently.
Operators work by taking one or more values (called operands) and producing a result. For example, in the expression 5 + 3, the + is the operator, and 5 and 3 are the operands. Python evaluates this and gives you 8.
Unlike a simple calculator that just adds or subtracts, Python operators can work with different data types and combine multiple operations in a single line. This flexibility is what makes operators so powerful.
Think of operators as the verbs in a sentence. Your variables are nouns (the "things"), and operators are the actions performed on those things. Just like in English where you might say "The price exceeds the budget," in Python you'd write price > budget. The > operator is the verb that connects your two nouns and expresses a relationship between them.
Here's another way to think about it: If variables are ingredients in a recipe, operators are the cooking instructions—"mix," "heat," "compare." Without operators, your ingredients just sit there. With operators, they transform into something useful!
This diagram shows the fundamental pattern: operators take values, perform an action, and produce a result. This result can be a number, a boolean (True/False), or another value you can use in your program.
Let's start with the most intuitive operators—the ones that do math. You've been using these since elementary school, but Python adds a few special ones that are incredibly useful.
# Let's work with two numbers
a = 10
b = 3
# Addition - combine two numbers
print(a + b) # Output: 13
# Subtraction - find the difference
print(a - b) # Output: 7
# Multiplication - repeat addition
print(a * b) # Output: 30
# Division - split into equal parts (always returns a float)
print(a / b) # Output: 3.3333333333333335
💡 Tip: Notice that regular division (/) always returns a decimal number (float), even if you divide evenly. 10 / 2 gives you 5.0, not 5.
a = 10
b = 3
# Floor division - divide and round DOWN to nearest whole number
print(a // b) # Output: 3 (not 3.33...)
# Modulo - get the REMAINDER after division
print(a % b) # Output: 1 (because 10 ÷ 3 = 3 remainder 1)
# Exponentiation - raise to a power
print(a ** b) # Output: 1000 (10 × 10 × 10)
💡 Real-world use case: The modulo operator (%) is perfect for checking if a number is even or odd. If number % 2 == 0, it's even. If number % 2 == 1, it's odd!
a, b = 7, 3 # Assign multiple variables in one line
# Perform all operations and print results
print(a + b) # Addition: 10
print(a - b) # Subtraction: 4
print(a * b) # Multiplication: 21
print(a / b) # Division: 2.3333333333333335
print(a // b) # Floor division: 2
print(a % b) # Modulo: 1
print(a ** b) # Exponentiation: 343 (7³)
Comparison operators let you ask questions about your data. Is this value bigger? Are these two things equal? These operators always return a boolean: True or False.
score = 85
passing_grade = 60
perfect_score = 100
# Equal to - checks if values are EXACTLY the same
print(score == passing_grade) # False (85 is not equal to 60)
# Not equal to - checks if values are DIFFERENT
print(score != passing_grade) # True (85 is different from 60)
# Greater than
print(score > passing_grade) # True (85 is greater than 60)
# Less than
print(score < perfect_score) # True (85 is less than 100)
# Greater than or equal to
print(score >= 85) # True (85 equals 85)
# Less than or equal to
print(score <= 90) # True (85 is less than 90)
⚠️ Critical Mistake Alert: The most common beginner error is using = when you mean ==. Remember: = assigns a value, == checks if values are equal!
a = 7
b = 3
# Compare and print results
print(a > b) # True - 7 is greater than 3
print(a == b) # False - 7 does not equal 3
print(not (a < b)) # True - it's NOT true that 7 < 3
Logical operators let you combine multiple comparisons. This is essential for making complex decisions in your code.
age = 25
has_license = True
has_insurance = True
# AND - both conditions must be True
can_drive = age >= 18 and has_license
print(can_drive) # True (both conditions are met)
# OR - at least one condition must be True
needs_documents = not has_license or not has_insurance
print(needs_documents) # False (has both documents)
# NOT - reverses the boolean value
is_minor = not (age >= 18)
print(is_minor) # False (25 is not a minor)
# Complex combination
can_rent_car = age >= 21 and has_license and has_insurance
print(can_rent_car) # True (all conditions met)
💡 Remember: and is strict (both must be True), or is flexible (at least one must be True), and not flips the value.
# Regular assignment
score = 100
# Add and assign (same as: score = score + 10)
score += 10
print(score) # 110
# Subtract and assign
score -= 5
print(score) # 105
# Multiply and assign
score *= 2
print(score) # 210
# Divide and assign
score /= 3
print(score) # 70.0
Let's put everything together with a practical exercise. You'll check if a student's score qualifies as passing and if it's in the honor range.
Create a new Python file called grade_checker.py and start with this:
# Student's test score
score = 87
# Define grade boundaries
passing_grade = 60
honor_grade = 85
# Check if score is passing (>= 60)
is_passing = score >= passing_grade
print("Is passing:", is_passing)
# Check if score is in honor range (>= 85)
is_honor = score >= honor_grade
print("Is honor grade:", is_honor)
# Check both conditions together
qualifies_for_honor = is_passing and is_honor
print("Qualifies for honor roll:", qualifies_for_honor)
Run your script with: python grade_checker.py
Expected Output:
Is passing: True
Is honor grade: True
Qualifies for honor roll: True
💡 Try This: Change the score to different values (like 55, 70, or 92) and see how the results change. This helps you understand how the operators work in different scenarios.
Problem: You try to compare values but accidentally assign instead.
Why it happens: In math class, we use = for "equals," but in Python, = assigns values.
Solution:
# WRONG ❌
if score = 100: # This tries to assign, not compare!
# CORRECT ✅
if score == 100: # This compares the values
Prevention: Read = as "gets the value" and == as "is equal to."
Problem: You get unexpected decimal results or whole numbers when you want the opposite.
Why it happens: Not understanding the difference between float and floor division.
Solution:
# / always returns a float (decimal)
print(10 / 3) # 3.3333333333333335
# // returns an integer (rounds down)
print(10 // 3) # 3
Prevention: Use / for accurate division, // when you want whole numbers only.
Problem: Your calculation produces unexpected results because operators are evaluated in the wrong order.
Why it happens: Python follows mathematical order of operations (PEMDAS).
Solution:
# WRONG - without parentheses
result = 10 + 5 * 2 # Result: 20 (multiplication happens first!)
# CORRECT - with parentheses for clarity
result = (10 + 5) * 2 # Result: 30
Prevention: When in doubt, use parentheses to make your intention clear.
Problem: Your condition logic doesn't work as expected.
Why it happens: Confusion about how and/or work together.
Solution:
# WRONG - this is always False if age is a single value
if age > 18 and age < 18: # Can't be both!
# CORRECT - check a range
if age >= 18 and age <= 65: # Between 18 and 65
Prevention: Think through the logic: "If both of these are true" (and) vs. "If either is true" (or).
Problem: The % operator returns unexpected values.
Why it happens: Thinking % means "percent" instead of "remainder."
Solution:
# % returns the REMAINDER after division
print(10 % 3) # 1 (because 10 ÷ 3 = 3 remainder 1)
print(15 % 4) # 3 (because 15 ÷ 4 = 3 remainder 3)
print(8 % 2) # 0 (evenly divides, no remainder)
Prevention: Remember: modulo = remainder. Perfect for checking even/odd or cycles!
Problem: Comparing a string to a number gives unexpected results.
Why it happens: Python can't meaningfully compare different types.
Solution:
# WRONG ❌
age = "25"
if age > 18: # Error! Can't compare string to int
# CORRECT ✅
age = int("25") # Convert to integer first
if age > 18: # Now it works!
Prevention: Make sure you're comparing values of the same type.
Project Goal: Build a tip calculator that automatically adjusts the tip percentage based on the bill amount.
Step 1: Create a file called tip_calculator.py
Step 2: Get the bill amount from the user:
# Get bill amount from user
bill = float(input("Enter bill amount: $"))
Step 3: Calculate the tip percentage based on bill amount:
# Determine tip percentage
# 15% for bills under $100, 20% for $100 or more
tip_percentage = 0.15 if bill < 100 else 0.20
Step 4: Calculate the tip amount and total:
# Calculate tip and total
tip_amount = bill * tip_percentage
total = bill + tip_amount
Step 5: Display the results nicely formatted:
# Display results
print(f"\nBill Amount: ${bill:.2f}")
print(f"Tip ({int(tip_percentage * 100)}%): ${tip_amount:.2f}")
print(f"Total Amount: ${total:.2f}")
# Smart Tip Calculator
print("=== Smart Tip Calculator ===\n")
# Get bill amount from user
bill = float(input("Enter bill amount: $"))
# Determine tip percentage (15% under $100, 20% for $100+)
tip_percentage = 0.15 if bill < 100 else 0.20
# Calculate tip and total
tip_amount = bill * tip_percentage
total = bill + tip_amount
# Display results
print(f"\nBill Amount: ${bill:.2f}")
print(f"Tip ({int(tip_percentage * 100)}%): ${tip_amount:.2f}")
print(f"Total Amount: ${total:.2f}")
=== Smart Tip Calculator ===
Enter bill amount: $85.50
Bill Amount: $85.50
Tip (15%): $12.82
Total Amount: $98.32
💡 Challenge Hint: For the bill splitting feature, you'll need another input and one more division operation. Think about where to add it in the code flow!
Congratulations! You've mastered the fundamental building blocks of Python programming. Here's what you now know:
+, -, *, /, //, %, **) let you perform mathematical calculations==, !=, >, <, >=, <=) let you compare values and make decisionsand, or, not) let you combine multiple conditions=, +=, -=) let you store and update values efficiently= (assignment) and == (comparison) is criticalNow that you understand operators, you're ready to make your programs truly intelligent with conditionals. Here's your action plan:
🚀 You're building momentum! Operators are fundamental to everything you'll do in Python. With this knowledge, you're now ready to write programs that can think, decide, and respond to different situations. The next step is learning how to use these comparisons to make your code branch in different directions—that's where conditionals come in!
Check your understanding with this quick quiz
1. What is the result of 17 % 5?
2. Which operator checks if two values are equal?
3. What does 10 // 3 return?
4. What will True and False evaluate to?
5. What is 2 ** 3 equal to?
6. What does not True evaluate to?