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.



Page 1: Intro

Page 2: The theory: learn what you need to know as fast as possible.

Page 3: Try it: try out and adapt some working python code snippets.

Page 4: Debug it: Learn how to find and fix common mistakes.

Page 5: Extend it: Choose a project idea to use your newfound python skills.