Project: Tip Calculator
A small project turns separate language features into one useful result. Compute the tip as bill × percent ÷ 100. Add it to the bill, divide by the number of people, then round the per-person amount to two decimal places.
Combine functions, arithmetic, and formatted output to split a restaurant bill.
Example check: Worked and guided code samples are checked against CPython 3.13. Practice uses Pyodide 0.29.5 (Python 3.13) in your browser. How we check lessons
Video lesson: Project: Tip Calculator
The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube
Jump to a chapter
Read the video transcript
Select a timestamp to watch that moment on YouTube.
- 00:00
Four friends have a forty dollar restaurant bill before the tip. They agree on a twenty percent tip and want to split the final total evenly. What should each person pay? Pause for a moment and work it out without Python. Twenty percent of forty is eight dollars. The group owes forty eight dollars, so each person pays twelve. Today we will turn that reasoning into a small Python project. The point is to make the steps visible, keep the calculation reusable, and format the result so another person can understand it. Along the way, we will check a second bill, look at a tempting percentage mistake, and discuss what happens when the total cannot be split exactly into cents.
- 00:43
Open the matching lesson on PythonLessonLab if you want to run each variation while you watch. Start by naming the three inputs: bill, tip percent, and people. The bill is the amount to which the tip applies. The percent is a whole-number percentage such as twenty, not the decimal value zero point two. People is the number of equal shares. These names make the function call almost read like the receipt: split bill, forty, twenty, four. Inside the function, first calculate the tip. Multiply the bill by twenty, then divide by one hundred. That division converts twenty percent to zero point two.
- 01:23
Forty times zero point two gives eight. A quick sanity check is useful: if the tip percentage is below one hundred, the tip should usually be smaller than the bill. Next add the tip to the bill, giving forty eight. Divide the whole total by four people, giving twelve. Notice the order. Dividing the bill first and then adding the entire tip to each person's share would charge the tip four times. Write the tip, total, and share on separate lines while learning, even if you later combine them. Intermediate names make incorrect output easier to diagnose. Now put the calculation in a function. A function lets us run the same formula for another table without copying and editing several lines.
- 02:08
The return value should be a number, because a caller might want to add shares, compare them, or put them into another calculation. The print statement handles the human-facing sentence. The f string displays a dollar sign and forces two digits after the decimal point. Formatting changes the displayed text; it does not change the underlying arithmetic. Run the completed example and confirm the message, each person pays twelve dollars and zero cents. Next test fifty four dollars, eighteen percent, and three people. Eighteen percent of fifty four is nine dollars and seventy two cents. The total is sixty three dollars and seventy two cents.
- 02:50
Three equal shares are twenty one dollars and twenty four cents. Before running, predict that result yourself, then compare with the guide example on the lesson page. Here is an edge case: ten dollars split three ways is three dollars and thirty three cents when each displayed share is rounded separately. Three such payments total only nine dollars and ninety nine cents. For a classroom estimate, this may be acceptable. A real payment workflow must choose who pays the leftover cent. One transparent approach converts the total to integer cents, uses divmod to get a base share and a remainder, and assigns one extra cent to as many people as the remainder indicates.
- 03:34
One thousand cents divided among three people becomes shares of three hundred thirty four, three hundred thirty three, and three hundred thirty three cents. Their sum is exactly one thousand. That allocation rule is an additional product decision. Our beginner function focuses on the basic calculation, but it is valuable to know where a simple formula stops being sufficient. Finally, ask what should happen when people is zero. Division by zero would raise an exception, and a negative group size has no useful meaning. A more robust version checks that people is positive, and that the bill and tip values follow the rules chosen for the application.
- 04:16
We can raise a ValueError with a helpful message before doing any arithmetic. The website's deeper guide has a short runnable validation example. The first common mistake is treating twenty percent as the number twenty. Multiplying forty by twenty produces eight hundred, which is far too large for a tip on a forty dollar bill. Dividing the percentage by one hundred is the missing step. A second mistake is dividing the bill among four people and then adding the full eight dollar tip to every share. Ten plus eight gives eighteen per person, or seventy two dollars collected overall, when the true group total is forty eight.
- 04:56
Add the tip once, then divide the combined total. A third trap is believing that displaying two decimals automatically solves every money issue. We just saw the missing cent when ten dollars is split three ways. If exact accounting matters, define a cent allocation rule rather than assuming independent rounding will reconcile. As a quick diagnostic, print the tip, total, and share separately when an answer looks surprising. Now pause the video and complete the tip calculator on the lesson page. Before pressing Run, calculate the forty dollar example by hand and predict twelve dollars. Then change the bill, percentage, or group size and predict the new amount before running again.
- 05:41
Try a zero percent tip as a simple boundary case: the group should split the original bill with nothing added. Use the task checker only after your own output matches your prediction. The checker also uses a different bill, which helps catch a solution that merely prints twelve instead of calculating from the inputs. Complete the three-question quiz to finish the lesson. If you want one extra challenge, build a second function that accepts a total in whole cents and returns shares whose sum always matches that total. The written guide on PythonLessonLab shows the divmod idea and the expected output. Link to this lesson is on screen, with a browser console, solved examples, hints, and common mistakes you can revisit at your own pace.
Understand the concept
Put the calculation in a function so the same code works for different bills. Keep numeric calculation separate from display formatting: the function returns a number, while an f-string prints a dollar amount with exactly two digits after the decimal point.
This simplified example uses floating-point numbers. Money applications with strict accounting rules usually use decimal.Decimal; that is a later topic. Assume the number of people is positive in this project.
- Percent means divide by 100
- A function can return the per-person amount
- {amount:.2f} formats two decimal places
See it step by step
Read the code, predict the output, then compare it with the result.
01. Find a tip
bill = 50
tip = bill * 10 / 100
print(tip)5.0Ten percent is ten divided by one hundred, so the tip on 50 is 5.
02. Split a tipped bill
bill = 30
tip = bill * 20 / 100
each = (bill + tip) / 3
print(each)12.0A 20% tip adds 6; the total 36 divided among three people is 12 each.
03. Format the price
amount = 12
print(f"Pay ${amount:.2f}")Pay $12.00The format specifier .2f displays a numeric amount with two decimal places.
A closer look
Follow the reasoning, inspect each result, then try the suggested changes in the console below.
Decide what the numbers mean
Before writing arithmetic, define the agreement at the table. Is the percentage applied to the food subtotal or to a total that already includes tax? Is the service charge already included? Python will faithfully calculate either interpretation, so the input names and the order of operations matter more than clever syntax. This example treats bill as the amount before the tip, with no separate tax or service charge.
A useful way to check the formula is to calculate the total first. For a bill of 54 and an 18 percent tip, 18/100 is 0.18, so the tip is 9.72. The group owes 63.72, and three equal shares are 21.24. Write those intermediate values down when debugging; a believable looking final number can still come from a wrong percentage base.
bill = 54.00
tip_rate = 18 / 100
tip = bill * tip_rate
total = bill + tip
share = total / 3
print(f"Tip: {tip:.2f}")
print(f"Total: {total:.2f}")
print(f"Each: {share:.2f}")Tip: 9.72
Total: 63.72
Each: 21.24- Convert 18 percent to 0.18 before multiplying the bill.
- Add the tip once, then divide the complete total among three people.
- Predict the share if the tip changes to 0 percent, then change the code to check.
Who pays the leftover cent?
Displaying each share to two decimal places does not guarantee that all displayed shares add back to the exact bill. Ten dollars split three ways gives 3.33 each when independently rounded, which totals 9.99. For casual estimates that may be acceptable; for a payment screen, one person needs to cover the remaining cent. Think in whole cents when the sum must reconcile.
The built-in divmod function gives both the common share and the remainder. Start with an integer number of cents, assign everyone the quotient, then give one extra cent to the first remainder people. The chosen ordering is a policy, not a mathematical necessity. This is a small example of why money software eventually needs an explicit rounding and allocation rule.
total_cents = 1000
people = 3
base, extra = divmod(total_cents, people)
shares = [base + (1 if person < extra else 0)
for person in range(people)]
print(shares)
print(sum(shares) == total_cents)[334, 333, 333]
True- divmod(1000, 3) produces 333 whole cents per person and one leftover cent.
- Only the first share receives the extra cent, so the sum remains 1000.
- Change total_cents to 1001 and predict which shares increase.
Reject inputs that make no sense
The core calculation assumes a positive number of people and nonnegative bill and tip values. If people is zero, division fails; if people is negative, the answer is numeric but useless. Validate these conditions at the boundary where values enter the program. A helpful error tells the caller what must change and keeps the actual calculation simple.
A function can raise ValueError for impossible inputs while still returning a number for valid ones. The caller decides whether to show that error to a person, ask for another entry, or log it. For this exercise, catch the error only around the demonstration call. Try changing the group size from zero to two and predict whether the except branch will run.
def per_person(total, people):
if total < 0:
raise ValueError("Total cannot be negative")
if people <= 0:
raise ValueError("People must be positive")
return total / people
try:
print(per_person(36, 0))
except ValueError as error:
print(error)
print(per_person(36, 3))People must be positive
12.0- Check the input before any division occurs.
- A named ValueError is caught by the caller, while the valid call returns 12.0.
- Replace zero with two to see the successful path.
Try it in Python
Edit the example and run it. Python starts in your browser the first time you click Run.
Python console
Ready to runNeed input()? Add one value per line
Your output appears here.
Need a hint?
Try tip = bill * tip_percent / 100, then total = bill + tip. Divide total by people and return round(result, 2). The f-string handles display only.
Complete the task and select Check task to verify your code.
Quick quiz
Three questions. You can change your answers and try again.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Using the percent as a multiplier
tip = bill * 20tip = bill * 20 / 100What happens: A 20% tip on 40 becomes 800 instead of 8.
Convert a percent to a fraction before multiplying.
Dividing before adding the tip
each = bill / people + tipeach = (bill + tip) / peopleWhat happens: The whole tip is charged to every person.
Add the tip once to the whole bill, then split the total.