Skip to contentSkip to navigation

Module 06 · Lesson 02

Project: Tip & Bill Splitter

Build a tip and bill splitter: read the bill, tip rate and number of people, work out the tip, total and fair shares in whole cents, and print a tidy receipt.

  • About 8 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Work out a percentage
  • Share in whole cents
  • Print a tidy receipt
  • Check before dividing

The splitter in four parts

Friends share a bill and a tip. The program works out a fair share for each and prints a tidy receipt.

  • Read

    The bill, the tip rate as a percentage and how many people are paying.

  • Check

    No negative bills and at least one person, before any maths happens.

  • Work it out

    A 15 percent tip on 40 is 40 * 15 / 100, which is 6.

  • Share fairly

    Count in whole cents so no cent goes missing, and say who pays any extra one.

Splitting bills everywhere

The same maths shows up wherever people pay together.

  • RestaurantsCard machines suggest tips of 10, 15 or 20 percent and split the total.
  • Shared ridesA taxi fare is split between everyone in the car.
  • Group presentsClassmates chip in for a gift, with someone covering the odd cent.
  • Shopping appsTax and discounts are percentages worked out the same way.

A percentage in one line

This line turns a tip rate into money. Tap each part to see its job.

Part 1 of 5

Tap any part of the code below, or press Next.1 of 5 explored

answer:Stores the tip, ready to add to the bill.

Build the splitter in five steps

Build the project one step at a time. Each example runs on its own: change it, then press Run.

Example 1 of 61. Percentages

A percentage is a number out of 100.

Your turn: Work out a 20 percent tip on a bill of 63.50.

Python
bill = 40
rate = 15
tip = bill * rate / 100
print("Tip:", tip)
print("Total:", bill + tip)
Output
Press Run to see what it prints.

Watch a bill split fairly

Press Step to run one line at a time. Three friends share a 50.00 bill with a 10 percent tip.

Ready. Press Step to run the first line.

  1. bill = 50.00
  2. rate = 10
  3. people = 3
  4. total_cents = round(bill * (100 + rate))
  5. share = total_cents // people
  6. extra = total_cents % people
  7. print(f"Each pays {share / 100:.2f}")
  8. print(f"{extra} cent left for one person")

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.A 15 percent tip on 80: what prints?

bill = 80
print(bill * 15 / 100)

0 of 6 answered

Common money maths misconceptions

Each card is something beginners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Building the splitter

The brief

A group finishes a meal. The program asks for the bill, the tip percentage and the number of people. It prints the tip, the total and how much each person pays. Shares must add up exactly to the total, and the program must not crash on silly input.

The plan

  1. Read the three values and convert them: the bill is a float, the tip and the number of people are whole numbers.
  2. Check them: the bill must not be negative, and there must be at least one person.
  3. Work out the tip and the total.
  4. Split the total into shares that add up exactly.
  5. Print a receipt.

Step 1 and 2: reading and checking

Try it 1: edit me, then Run
bill = float(input("Bill: "))
tip_percent = int(input("Tip %: "))
people = int(input("People: "))
if bill < 0 or people < 1:
    print("Please enter a bill of 0 or more and at least 1 person.")
Output
Press Run to see what it prints.

Dividing by people when it is 0 would raise ZeroDivisionError, so the check has to happen before any division. In the finished program, the rest of the work runs only in the else branch, or inside a function that returns early.

Percentages and rates

People say "a 15% tip", but the maths needs the rate 0.15. Decide once where that conversion happens and stick to it. In this project, functions take the percentage, such as 15, and divide by 100 inside, because that matches what the user types. Mixing the two styles is a classic bug: passing 0.15 to a function that expects 15 gives a tip a hundred times too small, and nothing crashes to warn you. A clear parameter name such as percent or rate and a one-line docstring prevent it. The same care applies to totals: decide whether tax is added before or after the tip, write the rule down, and test it with numbers you can check by hand.

Step 3: tip and total as functions

Each calculation gets its own small function that returns a value. Functions that return, rather than print, can be reused and tested, and the receipt code stays separate from the maths.

Try it 2: edit me, then Run
def tip_amount(bill, percent):
    return round(bill * percent / 100, 2)

def total_with_tip(bill, percent):
    return round(bill + tip_amount(bill, percent), 2)

print(tip_amount(36.0, 15))       # 5.4
print(total_with_tip(36.0, 15))   # 41.4
Output
Press Run to see what it prints.

round(x, 2) keeps the stored amount to whole cents. Displaying it is a separate job: f"{41.4:.2f}" shows 41.40, always with two decimal places.

Step 4: fair shares

Dividing 100.00 among 3 people gives 33.333..., which rounds to 33.33. Three shares of 33.33 add up to 99.99, so a cent has vanished. The reliable fix is to work in whole cents, which are integers and never have rounding errors.

Try it 3: edit me, then Run
def split_cents(total, people):
    cents = round(total * 100)
    base = cents // people
    extra = cents % people
    shares = []
    for i in range(people):
        shares.append(base + 1 if i < extra else base)
    return shares

print(split_cents(100.00, 3))     # [3334, 3333, 3333]
Output
Press Run to see what it prints.

// gives each person's base share in cents and % says how many cents are left over. Those leftover cents go one each to the first few people, so the shares differ by at most one cent and always add up to the total. Converting back for display is share / 100.

Floats are fine for multiplying a bill by a rate, as long as you round the result. But for anything that has to add up exactly, such as shares, balances and stock values, whole numbers of the smallest unit are the professional habit.

Step 5: the receipt

Formatting ties it together. A fixed width for the labels and a right-aligned money column make the numbers easy to compare.

Try it 4: edit me, then Run
def receipt(bill, percent, people):
    total = total_with_tip(bill, percent)
    print(f"{'Bill':<10}{bill:>8.2f}")
    print(f"{'Tip':<10}{tip_amount(bill, percent):>8.2f}")
    print(f"{'Total':<10}{total:>8.2f}")
    for number, cents in enumerate(split_cents(total, people), start=1):
        print(f"{'Person ' + str(number):<10}{cents / 100:>8.2f}")
Output
Press Run to see what it prints.

Notice how short receipt is. All the hard thinking lives in small functions with clear names, and the receipt simply calls them in order. That is the shape most good programs end up with.

Making it robust

A few more checks make the tool pleasant to use. Strip spaces from each answer before converting. Accept a tip typed as 15% by removing the percent sign with replace("%", ""). Ask again instead of quitting when an answer is invalid, using the same while True pattern as the guessing game. And test the edges: a bill of 0, one person, a tip of 0, and amounts that do not split evenly.

Ideas to extend it

Offer three tip choices and show the total for each. Let each person pay a different percentage of the bill. Add a service charge that some restaurants include automatically, and skip the tip when it is present. Each idea is one more small function and one more line in the receipt.

Syntax

The general shape of the statements in this lesson.

syntax.py
round(bill * percent / 100, 2)   # store whole cents
f"{amount:.2f}"                  # always two decimals
f"{label:<10}{amount:>8.2f}"     # aligned receipt line
cents = round(total * 100)       # money as an int
base, extra = cents // people, cents % people
if people < 1: ...               # check before dividing
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

A complete receipt

Beginner

Print a receipt for a bill of 86.50 with a 12% tip split between 3 people, with shares that add up exactly to the total.

Python
def tip_amount(bill, percent):
    return round(bill * percent / 100, 2)

def split_cents(total, people):
    cents = round(total * 100)
    base, extra = cents // people, cents % people
    shares = []
    for i in range(people):
        shares.append(base + 1 if i < extra else base)
    return shares

bill, percent, people = 86.50, 12, 3
tip = tip_amount(bill, percent)
total = round(bill + tip, 2)
print(f"{'Bill':<10}{bill:>8.2f}")
print(f"{'Tip':<10}{tip:>8.2f}")
print(f"{'Total':<10}{total:>8.2f}")
shares = split_cents(total, people)
for number, cents in enumerate(shares, start=1):
    print(f"{'Person ' + str(number):<10}{cents / 100:>8.2f}")
print("Check:", sum(shares) / 100 == total)
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The tip is rounded to cents as soon as it is worked out. The total of 9,688 cents does not divide by 3, so the first person pays one extra cent. The last line proves the shares add back up to the total exactly.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Shares that lose a cent

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
total = 100.00
share = round(total / 3, 2)
print(share * 3)
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints 99.99; one cent is missing

Write this instead

cents = round(100.00 * 100)
shares = []
for i in range(3):
    shares.append(cents // 3 + (1 if i < cents % 3 else 0))
print(sum(shares) / 100)

Why it happens

Each share is rounded down to 33.33, and the rounding errors add up.

In the real world

Where this shows up in software people use every day.

  1. Splitting a holiday cottage

    Travel

    Four friends rent a cottage for 731.00 and want each payment to be as equal as possible while still adding up to the exact price the owner asked for.

    Why Python fits

    73,100 cents divides by 4 exactly, so nobody pays an extra cent. Change the price to 731.01 and the first friend would pay one cent more, with the total still exact.

    Python
    price = 731.00
    friends = ["Ana", "Bo", "Cy", "Dee"]
    cents = round(price * 100)
    base, extra = cents // len(friends), cents % len(friends)
    for i, name in enumerate(friends):
        pay = base + (1 if i < extra else 0)
        print(f"{name:<4}{pay / 100:>8.2f}")
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Why not just use floats for everything?

Floats are approximate. For a single calculation that is rounded at once they are fine, but sums of many rounded amounts can drift by a cent. Whole cents never drift.

Who pays the extra cent?

In this project, the first people in the list. Any fair rule works as long as the shares add up; some apps rotate who pays it.

What about other currencies?

The same idea works with any smallest unit. Currencies without cents, such as the yen, simply use 1 as the unit instead of 100.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 6 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.