Project 12 of 13, for Yahya
Four-Function Calculator
Type a sum as text, get the answer, and survive bad input with try and except, until quit.
No account needed. Your work is kept in this browser until you sign up.
The brief
- YahyaEvery chart I see has numbers on it and I check them all, it's quick sums all day long.
- YahyaThe trouble is people type the numbers in, and they'll put twelve as a word, or 12*4, or divide by nothing.
- YahyaI want a calculator that takes a sum the way I'd write it and tells me when it's wrong, without crashing.
- PaulIt'll have to cope with a bad sum without falling over, which you haven't done yet.
Ask Sum? over and over. quit prints Done for today. and stops. Spaces at the ends don't matter.
A sum is a number, a space, one of + - * /, a space, and a number: 12.5 * 4.
- Write
calculate(a, op, b). It returnsaandbadded, taken away, multiplied or divided, depending onop, andNonefor any otherop. - A sum that works prints
= 50.00, always with two decimal places. - A sum that doesn't split into exactly three parts gets
Write it like 12 * 4, with spaces. - If either number isn't a number, print
Those aren't both numbers. - Dividing by zero gets
Nothing divides by zero. - Any other operator gets
Use +, -, * or /.
Catch the errors with try and except, each by name. Nothing typed at it should stop the program.
Sum? 12.5 * 4 = 50.00 Sum? 30 / 0 Nothing divides by zero. Sum? twelve + 4 Those aren't both numbers. Sum? 7 % 2 Use +, -, * or /. Sum? 12*4 Write it like 12 * 4, with spaces. Sum? quit Done for today.
What you learn
The lesson, step by step
When something goes wrong
When something goes wrong as a program runs, Python raises an exception: an error with a type and a message. You've met
ValueErrorandNameError. Dividing by zero raises aZeroDivisionError.Yahya's calculator will be asked to divide by zero, so you need to know where that error goes.
An exception inside a function doesn't stay there. It travels back up to the line that called the function, and if nothing catches it, the whole program stops. The example prints
Cutting the cake., then a traceback, and never reaches its last line. The traceback lists line 2, where it went wrong, and line 5, whereper_personwas called.The usual slip is to expect Python to skip the bad line and carry on. It doesn't.
Something goes wrong
The bill split between 6 people, then between 0.
Catching it
tryandexceptcatch an exception before it can stop the program.try:runs the indented block under it. If a line in that block raises the error named afterexcept, Python skips the rest of the block and runs theexceptblock instead. Then it carries on underneath.People will type
twelveat Yahya's calculator. It mustn't fall over.float("twelve")raises a ValueError, soGotnever prints. The example printsNot a number: twelve, thenCarrying on.Change line 1 totext = "12"and run it: now thetryfinishes and theexceptis skipped.The usual slip is to expect the rest of the
tryblock to run after the error. The moment a line fails, Python leaves the block.Which lines run
A price, typed as a word.
Each error by name
An
exceptonly catches the error it names.except ValueError:catches a ValueError, and any other error gets straight past it and stops the program.A calculator can go wrong in more than one way: a word for a number, or a zero to divide by. Each needs its own message.
So give each error its own
except, one under another, lined up with thetry. Python runs the first one that matches. The example tries three pieces of text and prints5.0,six isn't a number., thenNothing divides by zero.The usual slip is
except Exception:, which catches every error there is. It catches your own typos too, and hides them behind the wrong message.Try, and catch
The class fund has 30 pounds for snacks. This works out how much that is a week, from the weeks you type.
Only if it worked
else:after theexceptblocks runs only when nothing in thetrywent wrong.It keeps the
trysmall, around just the line that might fail, and gives the good answer a place of its own that an error can't reach.Here
float("4")works, so theexceptis skipped and theelseprints7.50 a week. Change line 1 totext = "four"and run it: theexceptruns, and theelsedoesn't.The usual slip is to think
elseruns every time, like the lines underneath. It only runs when thetryfinished without an error.Good answers only
Two lots of weeks, typed two ways.
How Paul would do it
- PaulI measured the Workshop for new desks with a tape that's half in inches, and I typed some odd things.
Paul's tape converter takes a measurement typed the way he'd write it,
32 in, and turns it into centimetres.He checks the shape first, two parts, with an
if. Then he puts the line that can fail in atry, catches each error by name with its own message, and prints the answer in anelse. A bad measurement never stops the program: the loop just goes round again.The labels beside the code are the steps he took. Yahya's calculator takes the same steps.
Fix Caitlin's version
- CaitlinI had a go at Yahya's calculator and nothing can crash it, because I catch everything.
- CaitlinThen he typed 2 + 2 and it said they weren't both numbers. Can you look? Something's off.
Run Caitlin's calculator, type
2 + 2, thenquit. It should print= 4.00.except Exception:catches every error there is, including the ones nobody expected, and hides them behind one message. Catch the error you mean, by name, and see what was hiding.Make the calculator
Build Yahya's calculator. The brief has the whole spec. The comments in the file are Paul's labels from the Workshop tape.
Sum? 12.5 * 4 = 50.00 Sum? 30 / 0 Nothing divides by zero. Sum? twelve + 4 Those aren't both numbers. Sum? quit Done for today.Let
calculatedivide by zero if it's asked to. TheZeroDivisionErrortravels back up to the line that called it, inside yourtry, and theexceptthere deals with it. For an operator it doesn't know,calculatereturnsNone.The checks call
calculateon its own, then type whole days of sums at the program: good ones, bad ones and some very bad ones, thenquit.Ship it
- YahyaTwelve and a half at four is fifty. Then I spent ten minutes typing rubbish at it.
- YahyaForty bad sums and it never fell over once, so it's staying open next to my data.