07: Python: Runtime errors

Debug it

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

If you want to get some top tips for making your code more robust and dealing with runtime errors you can jump ahead to the activity on Error Handling but you’re likely to need to understand sequence and selection first.

For now, it’s enough just to know that runtime errors happen when your code attempts to do something impossible and that you can make your code cope with these runtime errors using try and except

Below is some code that has been deliberately broken so that you can find, understand and cope with some some common runtime errors.

Challenges

  1. Fix the km to mile converter

    Line 9 and 14 should both ask a question, convert the answer to a float and then save that number to a variable. Line 9 is correct, but something’s missing from line 14.

  2. Make the miles to km converter say “Invalid number” if you type in something like “a long way”

    Lines 9, 10 and 11 will need to be surrounded with try: and except:so that you can display "Invalid number" when python tries and fails to convert "a long way" to a number.

  3. Make the km to miles converter say “Please try again” if you don’t type anything in

    This is very similar to challenge 2: use try and except to tell your code how to deal with the error without crashing.

On the next page you’ll get some ideas for projects that work with data of different types.

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