10: Logic Errors in Python

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

Leave a Reply

Your email address will not be published. Required fields are marked *