Python Operators Decoded: From Basic Math to Powerful Comparisons
Hey there, Python learner!
You know what blew my mind when I first learned Python? It wasn’t the fancy AI models or web scraping tools. It was the moment I realized that every single decision you make in life is basically a Python operator in disguise.
Think about it.
This morning, you checked if it was raining before deciding whether to carry an umbrella. That’s a comparison operator.
You decided to grab coffee and breakfast because you were hungry and tired. That’s a logical operator.
You calculated how much money you’d have left after buying that new phone. That’s an arithmetic operator.
Programming isn’t some abstract concept floating in the cloud — it’s literally how your brain works every single day.
And today? Today we’re going to decode how Python thinks. By the end of this post, you won’t just write code — you’ll understand the logic behind every decision your programs make.
Sound exciting? Let’s dive in.
What You’ll Master Today
By the end of this post, you’ll be able to:
✅ Perform complex calculations using arithmetic operators
✅ Make your programs smart with comparison operators
✅ Combine multiple conditions with logical operators
✅ Write cleaner code with assignment operator shortcuts
✅ Build a real BMI calculator that gives personalized health advice
Prerequisites: Variables and data types (check out my previous post!)
Quick Recap: Building on What We Know
Remember when we built this simple calculator?
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print(f"{num1} + {num2} = {num1 + num2}")That + symbol? That's an arithmetic operator. You've already been using operators without even realizing it!
Today, we’re going to expand your toolkit from basic math to making actual decisions.
Part 1: Arithmetic Operators — More Than Just Math
Let’s start with something familiar but take it deeper than you’ve ever gone before.
The Operators You Already Know
x = 10
y = 3
# Addition
result = x + y
print(f"{x} + {y} = {result}")
# Output: 10 + 3 = 13
# Subtraction
result = x - y
print(f"{x} - {y} = {result}")
# Output: 10 - 3 = 7
# Multiplication
result = x * y
print(f"{x} * {y} = {result}")
# Output: 10 * 3 = 30
# Division (always returns a float)
result = x / y
print(f"{x} / {y} = {result}")
# Output: 10 / 3 = 3.333...Nothing surprising yet, right? But here’s where it gets interesting.
The Secret Operators Nobody Talks About
1. Floor Division (//) - The "Give Me Whole Numbers" Operator
Ever tried to split a pizza among friends and needed to know how many whole slices each person gets?
pizza_slices = 17
people = 4
slices_per_person = pizza_slices // people
print(f"Total slices: {pizza_slices}")
print(f"Number of people: {people}")
print(f"Each person gets: {slices_per_person} slices")
# Output: Total slices: 17
# Output: Number of people: 4
# Output: Each person gets: 4 slicesReal-world use: Dividing items evenly, calculating pages, time conversions.
2. Modulus (%) - The "What's Left Over?" Operator
This is my favorite operator because it solves so many real-world problems.
pizza_slices = 17
people = 4
leftover = pizza_slices % people
print(f"Leftover slices: {leftover}")
# Output: Leftover slices: 1
# Check if a number is even or odd
number = 17
remainder = number % 2
print(f"{number} divided by 2 leaves remainder: {remainder}")
# Output: 17 divided by 2 leaves remainder: 1
# If remainder is 0, it's even. If remainder is 1, it's odd!More examples:
# Is it your turn? (in a game rotation)
turn_number = 15
players = 4
current_player = turn_number % players
print(f"Turn {turn_number}: Player {current_player}'s turn!")
# Output: Turn 15: Player 3's turn!
# Check divisibility
number = 20
divisor = 5
remainder = number % divisor
print(f"{number} % {divisor} = {remainder}")
# Output: 20 % 5 = 0
print("Since remainder is 0, 20 is perfectly divisible by 5!")Pro tip: Modulus is essential for checking divisibility, cycles, and rotations.
3. Exponentiation (**) - The Power Operator
Want to calculate compound interest? Population growth? This is your operator.
# Simple example first
base = 2
exponent = 3
result = base ** exponent
print(f"{base} to the power of {exponent} = {result}")
# Output: 2 to the power of 3 = 8
# Money grows exponentially
initial_investment = 1000
annual_rate = 1.08 # 8% growth
years = 5
growth_multiplier = annual_rate ** years
final_amount = initial_investment * growth_multiplier
print(f"Initial investment: ${initial_investment}")
print(f"After {years} years: ${final_amount:.2f}")
# Output: Initial investment: $1000
# Output: After 5 years: $1469.33Real-World Project: Shopping Cart Calculator
Let’s build something practical right now.
# Shopping Cart with Tax Calculator
print("Shopping Cart Calculator")
print("-" * 30)
# Item prices
item1_price = float(input("Enter price of item 1: $"))
item1_qty = int(input("Enter quantity: "))
item2_price = float(input("Enter price of item 2: $"))
item2_qty = int(input("Enter quantity: "))
# Calculate subtotal
subtotal = (item1_price * item1_qty) + (item2_price * item2_qty)
# Calculate tax (8%)
tax_rate = 0.08
tax = subtotal * tax_rate
# Calculate total
total = subtotal + tax
# Display results
print("\n" + "=" * 30)
print(f"Subtotal: ${subtotal:.2f}")
print(f"Tax (8%): ${tax:.2f}")
print(f"Total: ${total:.2f}")
print("=" * 30)
# Example Output:
# Enter price of item 1: $15.99
# Enter quantity: 2
# Enter price of item 2: $8.50
# Enter quantity: 3
#
# ==============================
# Subtotal: $57.48
# Tax (8%): $4.60
# Total: $62.08
# ==============================Try this yourself! Run it with different values. See how the operators work together?
Part 2: Comparison Operators — Teaching Your Code to Judge
Here’s where your code starts getting smart. Comparison operators let your program make decisions based on conditions.
The Six Operators That Return True or False
Remember booleans? (True and False)? Comparison operators always give you a boolean result.
age = 25
voting_age = 18
# Greater than
result = age > voting_age
print(f"{age} > {voting_age} = {result}")
# Output: 25 > 18 = True
# Less than
result = age < voting_age
print(f"{age} < {voting_age} = {result}")
# Output: 25 < 18 = False
# Greater than or equal
result = age >= 18
print(f"{age} >= 18 = {result}")
# Output: 25 >= 18 = True
# Less than or equal
result = age <= 30
print(f"{age} <= 30 = {result}")
# Output: 25 <= 30 = True
# Equal to (notice the double ==)
result = age == 25
print(f"{age} == 25 = {result}")
# Output: 25 == 25 = True
# Not equal to
result = age != 30
print(f"{age} != 30 = {result}")
# Output: 25 != 30 = TrueImportant: Notice == (comparison) vs = (assignment). This trips up everyone at first.
# WRONG - This is assignment
x = 5
# RIGHT - This is comparison
result = (x == 5)
print(result) # Output: TrueReal-World Examples
# Age verification
user_age = 16
can_vote = user_age >= 18
print(f"Age: {user_age}")
print(f"Can vote? {can_vote}")
# Output: Age: 16
# Output: Can vote? False
# Price comparison
item_price = 29.99
budget = 50.00
can_afford = item_price <= budget
print(f"Item price: ${item_price}")
print(f"Your budget: ${budget}")
print(f"Can afford? {can_afford}")
# Output: Item price: $29.99
# Output: Your budget: $50.0
# Output: Can afford? True
# Password check
entered_password = "python123"
correct_password = "python123"
password_match = entered_password == correct_password
print(f"Password correct? {password_match}")
# Output: Password correct? TrueThis reads like English: “if 70 is less than or equal to score, and score is less than or equal to 100”
Part 3: Logical Operators — Combining Conditions Like a Pro
Logical operators are where your code gets really intelligent. They let you combine multiple conditions to make complex decisions.
The Three Operators That Rule Them All
1. and - Both Conditions Must Be True
# Both conditions must be True for result to be True
age = 25
has_license = True
can_drive = age >= 18 and has_license
print(f"Age: {age}")
print(f"Has license: {has_license}")
print(f"Can drive? {can_drive}")
# Output: Age: 25
# Output: Has license: True
# Output: Can drive? True
# If either is False, result is False
age = 25
has_license = False
can_drive = age >= 18 and has_license
print(f"\nAge: {age}")
print(f"Has license: {has_license}")
print(f"Can drive? {can_drive}")
# Output: Age: 25
# Output: Has license: False
# Output: Can drive? FalseTruth table for and:
print(f"True and True = {True and True}") # True
print(f"True and False = {True and False}") # False
print(f"False and True = {False and True}") # False
print(f"False and False = {False and False}") # False2. or - At Least One Condition Must Be True
# At least one condition must be True
has_subscription = False
has_coupon = True
can_access = has_subscription or has_coupon
print(f"Has subscription: {has_subscription}")
print(f"Has coupon: {has_coupon}")
print(f"Can access premium? {can_access}")
# Output: Has subscription: False
# Output: Has coupon: True
# Output: Can access premium? TrueTruth table for or:
print(f"True or True = {True or True}") # True
print(f"True or False = {True or False}") # True
print(f"False or True = {False or True}") # True
print(f"False or False = {False or False}") # False3. not - Flip the Condition
# Reverses the boolean value
is_raining = False
should_go_out = not is_raining
print(f"Is it raining? {is_raining}")
print(f"Should go out? {should_go_out}")
# Output: Is it raining? False
# Output: Should go out? True
# Another example
is_weekend = True
need_to_work = not is_weekend
print(f"\nIs weekend? {is_weekend}")
print(f"Need to work? {need_to_work}")
# Output: Is weekend? True
# Output: Need to work? FalseTruth table for not:
print(f"not True = {not True}") # False
print(f"not False = {not False}") # TrueComplex Conditions in Action
# Loan eligibility checker
print("Loan Eligibility Checker")
print("-" * 40)
age = 28
income = 45000
credit_score = 720
has_bankruptcy = False
# Check all conditions
meets_age = age >= 21
meets_income = income >= 30000
meets_credit = credit_score >= 650
no_bankruptcy = not has_bankruptcy
# Combine all conditions
is_eligible = meets_age and meets_income and meets_credit and no_bankruptcy
print(f"Age: {age} (need >= 21): {meets_age}")
print(f"Income: ${income} (need >= $30000): {meets_income}")
print(f"Credit: {credit_score} (need >= 650): {meets_credit}")
print(f"No bankruptcy: {no_bankruptcy}")
print("-" * 40)
print(f"ELIGIBLE FOR LOAN: {is_eligible}")
# Example Output:
# Age: 28 (need >= 21): True
# Income: $45000 (need >= $30000): True
# Credit: 720 (need >= 650): True
# No bankruptcy: True
# ----------------------------------------
# ELIGIBLE FOR LOAN: TruePart 4: Assignment Operators — Write Less, Do More
You’ve been using = to assign values. But Python has shortcuts that'll make your code cleaner.
The Basic Assignment
score = 0 # Simple assignment
print(f"Initial score: {score}")
# Output: Initial score: 0The Powerful Shortcuts
score = 100
print(f"Starting score: {score}")
# Output: Starting score: 100
# Adding to existing value
# Long way:
score = score + 10
print(f"After adding 10: {score}")
# Output: After adding 10: 110
# Short way (do this!):
score += 10 # Same as: score = score + 10
print(f"After adding 10 more: {score}")
# Output: After adding 10 more: 120All the shortcuts:
# Start fresh
score = 100
# Addition assignment
score += 20 # score = score + 20
print(f"After += 20: {score}") # 120
# Subtraction assignment
score -= 15 # score = score - 15
print(f"After -= 15: {score}") # 105
# Multiplication assignment
score *= 2 # score = score * 2
print(f"After *= 2: {score}") # 210
# Division assignment
score /= 3 # score = score / 3
print(f"After /= 3: {score}") # 70.0
# Floor division assignment
score //= 2 # score = score // 2
print(f"After //= 2: {score}") # 35.0
# Modulus assignment
score %= 7 # score = score % 7
print(f"After %= 7: {score}") # 0.0
# Exponentiation assignment
score = 5
score **= 2 # score = score ** 2
print(f"5 squared: {score}") # 25Real-World Example: Game Score Tracker
print("Game Score Tracker")
print("-" * 40)
player_score = 0
multiplier = 1
print(f"Starting score: {player_score}\n")
# Level 1: Collect coins
print("Level 1: Collect coins")
coins_collected = 15
points = coins_collected * 10
player_score += points # Add points
print(f"Collected {coins_collected} coins")
print(f"Points earned: {points}")
print(f"Total score: {player_score}\n")
# Level 2: Defeat enemies
print("Level 2: Defeat enemies")
enemies_defeated = 8
points = enemies_defeated * 50
player_score += points # Add more points
print(f"Defeated {enemies_defeated} enemies")
print(f"Points earned: {points}")
print(f"Total score: {player_score}\n")
# Level 3: Boss defeated - double all points!
print("Level 3: Boss Battle")
boss_defeated = True # You won!
print(f"Boss defeated: {boss_defeated}")
# Use comparison to check
score_doubled = boss_defeated and player_score > 0
print(f"Should double score: {score_doubled}")
# Double the score
player_score *= 2 # Multiply by 2
print(f"BOSS DEFEATED! Score doubled!")
print(f"Final score: {player_score}\n")
# Example Output:
# Starting score: 0
#
# Level 1: Collect coins
# Collected 15 coins
# Points earned: 150
# Total score: 150
#
# Level 2: Defeat enemies
# Defeated 8 enemies
# Points earned: 400
# Total score: 550
#
# Level 3: Boss Battle
# Boss defeated: True
# Should double score: True
# BOSS DEFEATED! Score doubled!
# Final score: 1100These shortcuts make code more readable and professional!
Mini Control Flow Primer (Sneak Peek!)
Now, you might be wondering: “How do I make my program actually do different things based on these True/False values?”
Get Ajay Narayan’s stories in your inbox
Join Medium for free to get updates from this writer.
Great question! That’s where control flow comes in. We’ll cover this in our next post.
The Grand Project: Enhanced Calculator
Let’s combine everything we’ve learned:
print("=" * 50)
print("SUPER CALCULATOR")
print("=" * 50)
# Get two numbers
num1 = float(input("\nEnter first number: "))
num2 = float(input("Enter second number: "))
print("\n" + "-" * 50)
# Arithmetic operators
print("ARITHMETIC OPERATIONS:")
print(f"Addition: {num1} + {num2} = {num1 + num2}")
print(f"Subtraction: {num1} - {num2} = {num1 - num2}")
print(f"Multiplication: {num1} * {num2} = {num1 * num2}")
print(f"Division: {num1} / {num2} = {num1 / num2:.2f}")
print(f"Floor Division: {num1} // {num2} = {num1 // num2}")
print(f"Modulus: {num1} % {num2} = {num1 % num2}")
print(f"Exponentiation: {num1} ** {num2} = {num1 ** num2}")
print("\n" + "-" * 50)
# Comparison operators
print("COMPARISONS:")
print(f"{num1} > {num2} = {num1 > num2}")
print(f"{num1} < {num2} = {num1 < num2}")
print(f"{num1} >= {num2} = {num1 >= num2}")
print(f"{num1} <= {num2} = {num1 <= num2}")
print(f"{num1} == {num2} = {num1 == num2}")
print(f"{num1} != {num2} = {num1 != num2}")
print("\n" + "-" * 50)
# Logical checks
print("LOGICAL CHECKS:")
both_positive = (num1 > 0) and (num2 > 0)
at_least_one_positive = (num1 > 0) or (num2 > 0)
first_is_negative = not (num1 > 0)
print(f"Both numbers positive: {both_positive}")
print(f"At least one positive: {at_least_one_positive}")
print(f"First number is negative: {first_is_negative}")
print("\n" + "=" * 50)
print("Thanks for using Super Calculator!")
print("=" * 50)
# Example run:
# Enter first number: 10
# Enter second number: 3
#
# --------------------------------------------------
# ARITHMETIC OPERATIONS:
# Addition: 10.0 + 3.0 = 13.0
# Subtraction: 10.0 - 3.0 = 7.0
# Multiplication: 10.0 * 3.0 = 30.0
# Division: 10.0 / 3.0 = 3.33
# Floor Division: 10.0 // 3.0 = 3.0
# Modulus: 10.0 % 3.0 = 1.0
# Exponentiation: 10.0 ** 3.0 = 1000.0
#
# --------------------------------------------------
# COMPARISONS:
# 10.0 > 3.0 = True
# 10.0 < 3.0 = False
# 10.0 >= 3.0 = True
# 10.0 <= 3.0 = False
# 10.0 == 3.0 = False
# 10.0 != 3.0 = True
#
# --------------------------------------------------
# LOGICAL CHECKS:
# Both numbers positive: True
# At least one positive: True
# First number is negative: FalseThis program demonstrates every single operator we learned today!
Practice Challenges
Beginner Level
- Even or Odd Checker: Ask for a number and use
%to determine if it's even or odd. Print the result. - Temperature Classifier: Ask for temperature in Fahrenheit. Use comparison operators to check if it’s “Hot” (>80), “Comfortable” (60–80), or “Cold” (<60). Print all three checks.
Intermediate Level
3. Discount Calculator: Ask for purchase amount. Calculate discount: 10% if amount >= $100, 5% if amount >= $50, 0% otherwise. Use comparison operators to calculate discount.
4. Password Strength Checker: Ask for a password. Check: length >= 8, contains a number, contains uppercase. Use logical operators to combine checks.
Advanced Level
5. Grade Calculator: Ask for 3 test scores. Calculate average. Use operators to determine: average >= 90 (“A”), >= 80 (“B”), >= 70 (“C”), >= 60 (“D”), else (“F”). Print average and all grade checks.
Before You Go
Did this click for you? Hit that 👏 clap button (you can clap up to 50 times!)
Questions or stuck? Drop them in the comments below.
Want my next post too? Hit Follow to get notified the moment it drops.
You just learned how every decision in programming works. That’s not basic — that’s fundamental. You’re not just coding anymore. You’re thinking in Python.
P.S. — Try creating a “leap year checker” using operators: A year is a leap year if it’s divisible by 4, except for years divisible by 100 (unless they’re also divisible by 400). Drop your solution in the comments!
See you in the next post! 🐍✨







