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
Below is some code that has been deliberately broken so that you can find, understand and cope with some some common runtime errors.
- 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.
- 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
except:so that you can display
"Invalid number"when python tries and fails to convert
"a long way"to a number.
- 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.