Project 2 of 13, for Caitlin
Bill Splitter
Split a bill between a table of people, tip included, and show every share to the penny.
No account needed. Your work is kept in this browser until you sign up.
The brief
- CaitlinWe're having a class dinner on Friday at a place I picked, and it's six of us on one bill.
- CaitlinLast time we spent twenty minutes arguing about who had the extra garlic bread.
- CaitlinThen there was the tip on top, and nobody could work that out either.
- PaulIt'll have to do sums and listen to what people type, and you haven't done either of those yet.
Ask for the bill in pounds, the number of people sharing it, and the tip as a percentage. The bill and the tip can have a decimal point.
Add the tip to the bill, then split the total equally. Print the total with the tip, then what each person pays, both with two decimal places, the way money is written.
Bill? 41.40 People? 6 Tip (%)? 10 Total with tip: 45.54 Each pays: 7.59
What you learn
The lesson, step by step
Python does sums
Python can do sums. Write numbers without quotes, and Python treats them as numbers, not text.
+adds and-takes away.*multiplies, because a keyboard has no × key./divides.print(240 * 3)works the sum out first, then prints the answer:720Dividing with
/always gives a number with a decimal point, even when it divides exactly. So720 / 100is7.2, and6 / 2is3.0.That
3.0surprises people. It's still three./just always answers with a decimal point.Which sum comes first
When a sum has more than one sign in it, Python doesn't simply work from left to right. It uses the order from maths lessons:
- brackets first
- then
*and/ - then
+and-
So
2 + 3 * 4is14: the3 * 4happens first, then the 2 is added. Put brackets round the part you want done first, and(2 + 3) * 4is20. Signs of the same rank, like+and-, go left to right.The usual mistake is reading a sum left to right, like a sentence. When you're not sure which part comes first, add brackets. They cost nothing, and the next person to read your code won't have to work it out either.
Which sum first?
Caitlin's table had one bowl of chips at 4 and two drinks at 3, written here as one sum. Work it out in Python's order before you pick.
Names for values
A variable is a name for a value. A value is any piece of data, like a number or a string.
chips = 4makes the namechipsstand for 4: think of a label stuck on a box with 4 in it.After that,
chipswithout quotes means "whateverchipsholds". Soprint(chips)prints4, not the word.The
=sign doesn't mean "equals" as it does in maths. It means: work out the right side, then put the name on the answer. Sochips = chips * 2works out4 * 2, using the valuechipshas now, then moves the label to 8.The usual mistake is reading that line as an equation that can't be true.
A label on a box
Two more people at the table want a drink. Follow the label on
drinksfrom line 1 to line 3.Good names
You choose each variable's name, and Python has a few rules. A name can use letters, digits and the underscore
_. It can't have spaces, and it can't start with a digit. Python style is lower-case words joined by underscores, likedrink_price.Python doesn't care what a name means:
x = 240works just as well. People care. Name each variable for what it holds, and the code reads like a description of the job.drink_price * drinks_orderedsays what it works out;x * ydoesn't.The usual mistake is a space.
drink price = 240stops with an error, because Python sees two names side by side. Use an underscore instead.Pounds and pence
Two more signs, for splitting a number into whole parts. A till works in pence, so they're handy for money.
//divides and throws away whatever is left over:720 // 100is7, the whole pounds.%gives only what's left over, called the remainder:720 % 100is20, the pence. So 720 pence is 7 pounds and 20 pence.Both rank with
*and/, so they happen before+and-.The usual mistake is reading
%as per cent. In Python it has nothing to do with percentages: it means remainder. A 10 per cent tip is worked out with/, asbill * 10 / 100.Change the sums
A small program that works in pence, the way a till does. Each task changes one line, so you can see what follows from it.
Asking a question
input()lets a program ask a question. It shows the text in its brackets, waits for someone to type an answer and press Enter, then hands the answer back. Put a variable in front to keep it:answer = input("How many people? ").The answer always comes back as a string, even when someone types digits. Type
6, andanswerholds the text"6", not the number 6.*shows the difference. A number times 2 is doubled, but a string times 2 is the same text twice. So if you type6, the program on the right prints66.That's the usual surprise: people expect 12. To do sums with an answer, you first turn it into a number. That's coming up.
Listening
This asks a question, then prints the answer times 3. Think about what kind of value
input()hands back.What kind of value
Every value has a type: the kind of value it is.
type()tells you which.print(type(3))prints<class 'int'>, which is Python's way of saying "this is an int".Three types so far:
int, short for integer: a whole number, like3float: a number with a decimal point, like3.0or7.2str, short for string: text, like"3"
An int and a str can look exactly alike:
print(3)andprint("3")both show3. Sotype()is how you tell them apart. When a program does something strange, checking a type is often the first useful thing to do.type()doesn't change anything. It only tells you what's there.What type is a division?
Python works out the brackets from the inside: first
6 / 2, then the type of the answer. Think back to what/always gives.Text to a whole number
int()turns a string of digits into a whole number, an int.int("6")is the number 6, so you can do sums with it.The program on the right asks for the text on line 1, then turns it into a number on line 2.
people = int(people)works outint(people)first, then moves the labelpeopleonto the number. Type6and it prints12.The usual mistake is giving
int()text with a decimal point.int("2.5")doesn't round or guess: it stops with a ValueError, the error for a value Python can't use. And given a float,int(7.9)chops off the decimals and gives7. It never rounds.Text to a decimal number
float()turns a string into a float, a number with a decimal point. It reads"41.40"and"2.5", and whole numbers too:float("7")is7.0. Use it for anything that can have a decimal point, like a bill or a tip.Floats have one catch. Python stores numbers in binary, as ones and zeros, and most decimals can't be stored exactly that way. The difference is tiny, but sometimes it shows: the last line on the right prints
0.30000000000000004, not0.3.The usual mistake is trusting a float to come out neat. Money needs tidying before anyone sees it, and a few steps on you'll see how.
Seven twenty, nearly
Three drinks at 2.40 each. Caitlin would say seven twenty. Remember what the last step said about floats.
What type is it?
This asks how many, then doubles the answer, or tries to. Each task checks or changes what type of value
countholds.Values inside text
An f-string is a string with an
fjust before the opening quote. Inside it, anything in curly brackets{}is worked out, and its value is dropped into the text.So with
total = 45.54, the f-stringf"Total: {total}"is the textTotal: 45.54. The brackets can hold a variable or a whole sum, like{total / 6}.It's how you put numbers into a sentence, exactly where they belong, in one string you can read.
The usual mistake is forgetting the
f. Without it, the curly brackets are just characters, and the program printsTotal: {total}, name and brackets included.Money to the penny
Money is written with two decimal places:
2.50, not2.5, and never7.199999999999999.In an f-string, put
:.2fafter the value inside the curly brackets:{each:.2f}. It means "show this number with two decimal places". It rounds what's shown and adds zeros to fill both places, so the last line on the right printsEach pays: 2.50.Python also has
round().round(each, 2)rounds the number itself to two places, but it never adds a zero, so it gives2.5. Fine for sums; not for a bill.The usual mistake is thinking
:.2fchanges the number. It doesn't:eachstill holds2.5. Only what's shown changes.Rounding money
Three drinks at 2.40 again, as in the Quick check on floats. This time the total is shown three ways.
How Paul would do it
- PaulThe floors are sharing the cost of network cable for the servers, which is basically your problem with a different bill.
A program with the same shape as the bill splitter. The floors are sharing the cost of network cable, at 1.20 a metre. With
4.5metres and2floors, each floor pays 2.70. Without the:.2f, Python would show 2.6999999999999997.Look at the names:
totalandeachsay what they hold, and your bill splitter uses the same two. The sums stay as floats to the end, and only the f-strings round, so no penny is lost on the way.The four labels beside the code are Paul's steps. Your file for the Build starts with the same four, as comments.
Fix Yahya's version
- YahyaI've already done the tip bit for Caitlin, just three letters and one line of maths, nice and fast.
- YahyaTwenty pounds with a ten per cent tip comes out at twenty pounds ten, and Caitlin says that's wrong. Can you look?
Yahya's program adds a tip to a bill. He asks and converts in one line:
float(input("Bill? "))works from the inside out, asking first, then turning the answer into a float.Run it with a bill of
20and a tip of10. A 10 per cent tip is 10 hundredths of the bill, so it should sayTotal with tip: 22.00.Work out which part of line 3 Python does first, then fix it. While you're in there, give the variables honest names. Paul won't accept
a,bandc.Make the bill splitter
Now the bill splitter, for the class dinner and every table after it. It asks three questions, then prints two lines:
Bill? 41.40 People? 6 Tip (%)? 10 Total with tip: 45.54 Each pays: 7.59Your file starts with the four steps from Paul's cable program, as comments. Under each, write the lines that do it:
- Ask for the bill, the people and the tip with
input(). - Turn them into numbers:
float()for the bill and the tip, which can have a decimal point (a 12.5 per cent service charge is common), andint()for the people. - Add the tip, as in Yahya's fix, then share the
totalout aseach. - Show both with
:.2f.
The checks try the class dinner and other tables, including one person paying the lot, a share like 2.40 that ends in a zero, and a 12.5 per cent tip.
- Ask for the bill, the people and the tip with
Ship it
- CaitlinForty-one forty, plus ten per cent is four fourteen, which makes forty-five fifty-four.
- CaitlinThat's seven fifty-nine each between six of us, all sorted before pudding, and next time it's pizza.