Easy
  Python
    Guide
Operators
Python operators are the fundamental building blocks that allow you to perform operations on data, much like mathematical symbols you'd use in everyday calculations. Think of operators as the verbs of programming - they tell Python what action to perform on your data. There are several types of operators including arithmetic (for maths), comparison (for testing conditions), logical (for combining conditions), and assignment (for storing values). These operators are essential for creating dynamic programs that can process information, make decisions, and respond to different situations.
Arithmetic operators (+, -, *, /, %, //, ) are perhaps the most intuitive as they mirror basic mathematical operations. You'll use these constantly in real-world scenarios like calculating totals in a shopping application (total_cost = item_price * quantity + delivery_fee), working out ages from birth years (age = current_year - birth_year), or determining if a number is even using the modulo operator (is_even = number % 2 == 0). The power operator () is brilliant for compound interest calculations (final_amount = principal * (1 + interest_rate) ** years), whilst floor division (//) helps when you need whole numbers, such as determining how many complete weeks are in a given number of days (weeks = total_days // 7).
Comparison operators (==, !=, <, >, <=, >=) are crucial for creating programs that make decisions based on conditions. These operators return True or False, which becomes the foundation for if statements and loops. In a login system, you might check if entered_password == stored_password: to verify credentials. For an online shop, you could use if customer_age >= 18: to determine if someone can purchase age-restricted items. Temperature monitoring systems might use if temperature > 30: to trigger cooling systems, whilst grade calculation programs could employ if score >= 70: to determine pass or fail status.
Logical operators (and, or, not) allow you to combine multiple conditions, creating more sophisticated decision-making logic. These are invaluable when you need to check several criteria simultaneously. For instance, a cinema booking system might use if age >= 18 and has_valid_id: to allow entry to an 18-rated film. A weather application could determine suitable outdoor conditions with if temperature > 15 and not is_raining:. In user validation, you might check if len(password) >= 8 and has_special_character or is_admin: to enforce password complexity rules whilst allowing administrators different access levels.
Assignment operators begin with the basic = for storing values (name = "Alice"), but Python offers compound assignment operators (+=, -=, *=, /=) that modify existing values efficiently. These are particularly useful in loops and accumulative operations. In a points-scoring game, you'd use player_score += bonus_points to add to existing scores. For inventory management, stock_quantity -= items_sold updates remaining stock levels. Shopping cart applications frequently employ cart_total += item_price as customers add items. These operators make code more readable and less prone to typing errors compared to writing total = total + new_value repeatedly, especially when dealing with longer variable names or complex calculations.
Syntax
Some examples of the syntax of operators:
# Example 1: Shopping Cart Total Calculation
item_price = 25.99
quantity = 3
delivery_fee = 4.50
total_cost = item_price * quantity + delivery_fee # 25.99 * 3 + 4.50 = 82.47
print(f"Total cost: £{total_cost}")
# Example 2: Age Verification System
current_year = 2025
birth_year = 1995
customer_age = current_year - birth_year # 2025 - 1995 = 30
can_buy_alcohol = customer_age >= 18 # True (30 >= 18)
print(f"Customer age: {customer_age}, Can buy alcohol: {can_buy_alcohol}")
# Example 3: Password Validation
password = "MySecure123!"
min_length = 8
has_numbers = any(char.isdigit() for char in password)
is_valid = len(password) >= min_length and has_numbers # True and True = True
print(f"Password is valid: {is_valid}")
# Example 4: Temperature Monitoring System
temperature = 32
humidity = 65
is_hot = temperature > 30 # True (32 > 30)
is_humid = humidity > 60 # True (65 > 60)
needs_aircon = is_hot or is_humid # True or True = True
print(f"Air conditioning needed: {needs_aircon}")
# Example 5: Game Score Tracking
player_score = 150
bonus_points = 25
penalty = 10
player_score += bonus_points # 150 + 25 = 175
player_score -= penalty # 175 - 10 = 165
print(f"Final score: {player_score}")
# Example 6: Even/Odd Number Checker
number = 47
is_even = number % 2 == 0 # 47 % 2 = 1, so 1 == 0 is False
is_odd = not is_even # not False = True
print(f"{number} is odd: {is_odd}")
# Example 7: Compound Interest Calculator
principal = 1000
interest_rate = 0.05 # 5%
years = 3
final_amount = principal * (1 + interest_rate) ** years # 1000 * 1.05^3 = 1157.63
print(f"Investment after {years} years: £{final_amount:.2f}")
# Example 8: Working Days Calculator
total_days = 100
weekend_days = 2
working_days_per_week = 5
complete_weeks = total_days // 7 # 100 // 7 = 14
remaining_days = total_days % 7 # 100 % 7 = 2
total_working_days = complete_weeks * working_days_per_week + min(remaining_days, working_days_per_week)
print(f"Working days in {total_days} days: {total_working_days}")
# Example 9: Login Attempt Security
max_attempts = 3
failed_attempts = 2
account_locked = False
failed_attempts += 1 # 2 + 1 = 3
should_lock = failed_attempts >= max_attempts and not account_locked # True and True = True
print(f"Should lock account: {should_lock}")
# Example 10: Discount Eligibility System
purchase_amount = 85.00
is_member = True
minimum_spend = 50.00
member_discount_threshold = 75.00
qualifies_for_discount = purchase_amount >= minimum_spend # True (85 >= 50)
gets_member_bonus = is_member and purchase_amount >= member_discount_threshold # True and True = True
discount_rate = 0.15 if gets_member_bonus else 0.10 if qualifies_for_discount else 0.00
final_price = purchase_amount * (1 - discount_rate) # 85 * (1 - 0.15) = 72.25
print(f"Original: £{purchase_amount}, Final: £{final_price:.2f}, Member bonus applied: {gets_member_bonus}")