Try it:

Find and fix common errors in your code
Logic errors in python: Find and fix common errors in your code

Below you’ll see some example python code that attempts to calculate the area and perimeter of a rectangle.

Logic errors in the code mean that whilst the program does exactly what it’s told to do without crashing, it doesn’t do what it’s supposed to do (it gets the calculations wrong)

Press Ctrl + Enter  to run the code.

This code will run without crashing but it doesn’t calculate the correct results.

The area of a rectangle should be the width multiplied by the height.

The perimeter of a rectangle should be the sum of the width, the height, the width again and the height again in order to calculate the distance all the way around the edge.

Challenges:

Start by running the code and testing it with a variety of different answers to the questions.

  1. Fix the logic error on line 10 when displaying the perimeter

    The code has been told to display the area instead of the perimeter. It won’t crash but it will do what the code says rather than what we want it it to do. That’s a logic error and needs changing.

  2. Fix the logic error on line 9 when calculating the perimeter

    The perimeter of a rectangle means the distance you’d have to travel to go all the way around the edge. It should be the width plus the height plus the width again plus the height again

  3. Fix the logic error on line 12 when checking if the shape is square

    A rectangle is a square if the height and width are the same length. Line 12 has got this the wrong way round and needs to use == rather than != to mean equal to rather than not equal to

On the next page you’ll get some code with both syntax and logic errors

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.