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



KPRIDE

KPRIDE stands for Keywords, Predict, Run, Investigate, Debug and Extend and it’s a way of helping you explore and understand python code. Click on the image below for a set of KPRIDE activities for this python skill.

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.