Paul's Python CoursePPC

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.

About 70 minutes, in 13 steps, free and with no account needed.

Start the project

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.

  1. Write calculate(a, op, b). It returns a and b added, taken away, multiplied or divided, depending on op, and None for any other op.
  2. A sum that works prints = 50.00, always with two decimal places.
  3. A sum that doesn't split into exactly three parts gets Write it like 12 * 4, with spaces.
  4. If either number isn't a number, print Those aren't both numbers.
  5. Dividing by zero gets Nothing divides by zero.
  6. Any other operator gets Use +, -, * or /.

Catch the errors with try and except, each by name. Nothing typed at it should stop the program.

What it prints
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

  1. 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 ValueError and NameError. Dividing by zero raises a ZeroDivisionError.

    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, where per_person was called.

    The usual slip is to expect Python to skip the bad line and carry on. It doesn't.

  2. Something goes wrong

    The bill split between 6 people, then between 0.

  3. Catching it

    try and except catch 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 after except, Python skips the rest of the block and runs the except block instead. Then it carries on underneath.

    People will type twelve at Yahya's calculator. It mustn't fall over.

    float("twelve") raises a ValueError, so Got never prints. The example prints Not a number: twelve, then Carrying on. Change line 1 to text = "12" and run it: now the try finishes and the except is skipped.

    The usual slip is to expect the rest of the try block to run after the error. The moment a line fails, Python leaves the block.

  4. Which lines run

    A price, typed as a word.

  5. Each error by name

    An except only 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 the try. Python runs the first one that matches. The example tries three pieces of text and prints 5.0, six isn't a number., then Nothing 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.

  6. 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.

  7. Only if it worked

    else: after the except blocks runs only when nothing in the try went wrong.

    It keeps the try small, 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 the except is skipped and the else prints 7.50 a week. Change line 1 to text = "four" and run it: the except runs, and the else doesn't.

    The usual slip is to think else runs every time, like the lines underneath. It only runs when the try finished without an error.

  8. Good answers only

    Two lots of weeks, typed two ways.

  9. 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 a try, catches each error by name with its own message, and prints the answer in an else. 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.

  10. 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, then quit. 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.

  11. 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 calculate divide by zero if it's asked to. The ZeroDivisionError travels back up to the line that called it, inside your try, and the except there deals with it. For an operator it doesn't know, calculate returns None.

    The checks call calculate on its own, then type whole days of sums at the program: good ones, bad ones and some very bad ones, then quit.

  12. 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.