07: Python: Runtime errors

Try it:

Find and fix common errors in your code
Python runtime errors: Find and fix common errors in your code

Below you’ll see some example python code that works out the size of each slice of cake you need to cut if you’re sharing it between any number of people.

Press Ctrl + Enter  to run the code.

This code doesn’t give you a score – you just need to investigate what happens when you run it and test it with different values.

Any line of code that starts with a #  is a comment: it doesn’t affect how the program runs, it’s just there to help explain what the code does.

Challenges:

These first set of challenges are just to show you what a runtime error is and when you might come across them. You don’t need to fix them yet.

  1. See what happens when you type in 10 people or 5 people

    These values are called normal or typical test data because they’re the sort of thing you’d expect a normal person to type in under normal conditions

  2. See what happens when you type in 0

    Line 12 will attempt to divide 360 by 0, which is impossible. Try dividing any number by 0 on a calculator – it’ll give you an error message too. This is a runtime error because the program runs and then crashes when it attempts to do something impossible.

  3. See what happens when you type in “five”

    five” is a string (text) which the code will attempt to convert to a number because of the int() function on line 9. Because this is impossible, you’ll get a runtime error here too.

Once you’ve seen the runtime errors crashing your program, try typing in the same things to test the following code:

Notice how:

1) try: appears just before where the runtime error might happen

2) all of the code that might potentially crash has been indented to the right

3) except: appears under the code that might crash

4) the code indented under except: tells python what to do instead of crashing

3 thoughts on “07: Python: Runtime errors

  • Pingback: Python for beginners: free interactive self marking activities

  • October 27, 2018 at 8:39 pm
    Permalink

    For some reason when I save my code it doesn’t give me a new url to use, do you know why this is?

    Reply
    • October 27, 2018 at 9:02 pm
      Permalink

      Hi Lucas. Sorry it’s not giving you a new url.
      When you change the code in one of these tracked activities it will automatically save your changes just on your computer in a cookie so that if you refresh your page you don’t have to start all over again. If you want a new URL you’ll have to press Ctrl+S. You may have to tick the ‘I’m not a robot’ box if that comes up on screen. This is irritating but it limits people exploiting the fact that anyone can save without having to log in. If you’re still having problems, reply here and I’ll email you.

      Reply

Leave a Reply