Python operators exercises solutions cheat sheet

Python operators exercises — 5 solved with solutions and cheat sheet

Python operators exercises with real context are the best way to cement what you learned in theory and practice.

In this article you’ll find five exercises across three levels: basic, intermediate and final challenge, with special focus on % and // the operators that confuse the most.

As always: try to solve it, use the hint if you’ve been stuck for more than 10 minutes, and compare with the commented solution at the end. You can use pythontutor.com to deepen your understanding step by step.

How to use this article

Read the exercise → try to solve it in VS Code → if you’re not making progress, read the hint → compare your solution with the one at the end. Don’t jump straight to the solutions — you learn twice as much by solving it yourself.

These Python operators exercises are ordered from least to most difficult so you can go at your own pace.


Python operators exercises — Basic Level

Exercise 1 — Gym invoice

A gym charges a base monthly fee of 29.99€. If a member has been a member for more than 12 months, they get a 10% discount. Write a program that asks for how many months the member has been enrolled and calculates how much they pay this month, how much they’ve paid in total, and how much they’ve saved if they have a discount.

The output should look like this:

Months as a member: 15

--- Gym invoice ---
Base fee:          29.99 €
Discount (10%):    -3.0 €
This month's fee:  26.99 €
Total paid:        434.85 €
Total savings:     9.0 €

💡 Hint: Use * to calculate the discount and the total paid. The total paid is the first 12 months at full price plus the remaining months at the discounted rate. Use // and % to split the months into two periods.


Exercise 2 — Time converter

Write a program that asks for a number of seconds and converts it to hours, minutes and seconds. For example, 3723 seconds is 1 hour, 2 minutes and 3 seconds.

The output should look like this:

Seconds: 3723

3723 seconds is:
→ 1 hour(s)
→ 2 minute(s)
→ 3 second(s)

💡 Hint: This exercise is pure // and %. Hours = seconds // 3600. Remaining minutes = (seconds % 3600) // 60. Remaining seconds = seconds % 60.


Python operators exercises — Intermediate Level

Exercise 3 — Grade analyser

Write a program that asks for a grade from 0 to 100 and calculates: the grade out of 10, the percentage it represents, whether the student passed (≥50 out of 100), how many points they need to reach the next level (merit ≥70, distinction ≥90), and how many points they have above the pass mark.

Grade (0-100): 73

--- Grade analysis ---
Grade out of 10:     7.3
Percentage:          73.0%
Passed?:             True
Next level:          Distinction (17 points to go)
Points above pass:   23

💡 Hint: Grade out of 10 = grade / 10. Percentage is the grade directly. For points needed, compare with 70 and 90 using > and -. Use % to calculate how many points are above the pass mark.


Exercise 4 — Digit extractor

Write a program that asks for a 4-digit integer and extracts each digit separately using only // and %. No strings, no converting to text — pure mathematical operators.

4-digit number: 2847

--- Digits of 2847 ---
Thousands: 2
Hundreds:  8
Tens:      4
Units:     7
Sum of digits: 21
Divisible by 3?: True  (because the sum of digits is divisible by 3)

💡 Hint: Units = n % 10. Tens = (n // 10) % 10. Hundreds = (n // 100) % 10. Thousands = n // 1000. Divisibility by 3 is checked with sum % 3 == 0.


Python operators exercises — Final Challenge

Exercise 5 — Cash register

This exercise mixes all the operators. Write a program that simulates a basic cash register. Ask for the total purchase amount and the money handed over by the customer, and calculate the change broken down into bills and coins (from largest to smallest: 50€, 20€, 10€, 5€, 2€, 1€, 0.50€, 0.20€, 0.10€, 0.05€, 0.02€, 0.01€).

Purchase amount (€): 37.43
Money given (€): 50

--- Cash register ---
Amount:    37.43 €
Given:     50.0 €
Change:    12.57 €

--- Change breakdown ---
1 x 10 € bill
1 x 2 € coin
1 x 0.50 € coin
1 x 0.05 € coin
1 x 0.02 € coin

💡 Hints:

  • Convert change to cents by multiplying by 100 and rounding with int(round(...)), avoids floating point errors
  • For each denomination: quantity = change_cents // denomination then change_cents = change_cents % denomination
  • Denominations in cents: 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1
  • Only show denominations where the quantity is greater than 0

Commented solutions

Solution Exercise 1:

# Gym invoice
BASE_FEE = 29.99
DISCOUNT = 0.10
MIN_MONTHS = 12

months = int(input("Months as a member: "))

if months > MIN_MONTHS:
    discount_euros = round(BASE_FEE * DISCOUNT, 2)
    monthly_fee = round(BASE_FEE - discount_euros, 2)
    months_with_discount = months - MIN_MONTHS
    total = round(BASE_FEE * MIN_MONTHS + monthly_fee * months_with_discount, 2)
    savings = round(discount_euros * months_with_discount, 2)
else:
    discount_euros = 0
    monthly_fee = BASE_FEE
    total = round(BASE_FEE * months, 2)
    savings = 0

print(f"\n--- Gym invoice ---")
print(f"Base fee:          {BASE_FEE} €")
print(f"Discount (10%):    -{discount_euros} €")
print(f"This month's fee:  {monthly_fee} €")
print(f"Total paid:        {total} €")
print(f"Total savings:     {savings} €")

Solution Exercise 2:

# Time converter
seconds = int(input("Seconds: "))

hours = seconds // 3600
remaining_minutes = (seconds % 3600) // 60
remaining_secs = seconds % 60

print(f"\n{seconds} seconds is:")
print(f"→ {hours} hour(s)")
print(f"→ {remaining_minutes} minute(s)")
print(f"→ {remaining_secs} second(s)")

Solution Exercise 3:

# Grade analyser
grade = float(input("Grade (0-100): "))

grade_out_of_10 = round(grade / 10, 1)
percentage = grade
passed = grade >= 50

if grade < 70:
    next_level = "Merit"
    points_needed = round(70 - grade, 1)
elif grade < 90:
    next_level = "Distinction"
    points_needed = round(90 - grade, 1)
else:
    next_level = "Already at distinction"
    points_needed = 0

points_above_pass = round(grade - 50, 1) if grade >= 50 else 0

print(f"\n--- Grade analysis ---")
print(f"Grade out of 10:     {grade_out_of_10}")
print(f"Percentage:          {percentage}%")
print(f"Passed?:             {passed}")
if points_needed > 0:
    print(f"Next level:          {next_level} ({points_needed} points to go)")
else:
    print(f"Level:               {next_level}")
print(f"Points above pass:   {points_above_pass}")

Solution Exercise 4:

# Digit extractor
n = int(input("4-digit number: "))

units     = n % 10
tens      = (n // 10) % 10
hundreds  = (n // 100) % 10
thousands = n // 1000

total = units + tens + hundreds + thousands
divisible_by_3 = total % 3 == 0

print(f"\n--- Digits of {n} ---")
print(f"Thousands: {thousands}")
print(f"Hundreds:  {hundreds}")
print(f"Tens:      {tens}")
print(f"Units:     {units}")
print(f"Sum of digits: {total}")
print(f"Divisible by 3?: {divisible_by_3}  (because the sum of digits is divisible by 3)")

Solution Exercise 5:

# Cash register
amount = float(input("Purchase amount (€): "))
given = float(input("Money given (€): "))

change = round(given - amount, 2)
change_cents = int(round(change * 100))

denominations = [5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1]
names = ["50 €", "20 €", "10 €", "5 €", "2 €", "1 €",
         "0.50 €", "0.20 €", "0.10 €", "0.05 €", "0.02 €", "0.01 €"]

print(f"\n--- Cash register ---")
print(f"Amount:    {amount} €")
print(f"Given:     {given} €")
print(f"Change:    {change} €")
print(f"\n--- Change breakdown ---")

for i in range(len(denominations)):
    quantity = change_cents // denominations[i]
    change_cents = change_cents % denominations[i]
    if quantity > 0:
        label = "bill" if denominations[i] >= 500 else "coin"
        print(f"{quantity} x {names[i]} {label}")

Cheat sheet — Python operators

# ============================================
# CHEAT SHEET — Python Operators
# Sergio Learns · sergiolearns.com
# ============================================

# ARITHMETIC OPERATORS
5 + 3     # addition       → 8
5 - 3     # subtraction    → 2
5 * 3     # multiply       → 15
5 / 2     # divide         → 2.5  (always float)
5 // 2    # floor division → 2    (integer, rounds down)
5 % 2     # modulo         → 1    (remainder, NOT percentage)
5 ** 2    # power          → 25

# COMMON TRAPS
10 / 2    # → 5.0  NOT 5 (it's float)
10 // 2   # → 5    this IS integer
# "%" is NOT percentage — it's the REMAINDER of division

# COMPARISON OPERATORS (return bool)
5 > 3     # → True
5 < 3     # → False
5 >= 5    # → True
5 <= 4    # → False
5 == 5    # → True   (equal — DOUBLE ==)
5 != 3    # → True   (not equal)

# WATCH OUT: = assigns, == compares
x = 5         # assignment — stores the value
x == 5        # comparison — returns True

# LOGICAL OPERATORS
True and True   # → True  (both must be True)
True or False   # → True  (at least one True)
not True        # → False (inverts)

# COMPOUND ASSIGNMENT
x += 5    # x = x + 5
x -= 3    # x = x - 3
x *= 2    # x = x * 2
x /= 4    # x = x / 4
x //= 2   # x = x // 2
x %= 3    # x = x % 3
x **= 2   # x = x ** 2

# PRECEDENCE (high to low)
# 1. ( )    parentheses
# 2. **     power
# 3. * / // %
# 4. + -
# 5. > < >= <= == !=
# 6. not
# 7. and
# 8. or

# CLASSIC % USES
n % 2 == 0          # even or odd
n % x == 0          # divisible by x
n % 10              # last digit
(n // 10) % 10      # second to last digit
n // 1000           # first digit of 4-digit number

# TIME CONVERSION WITH // AND %
hours   = seconds // 3600
minutes = (seconds % 3600) // 60
secs    = seconds % 60

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *