Errors in Python
Look at some common errors and mistakes and how to avoid them.
It is important to realize that making mistakes in code, just like in life, is normal. The important thing is to learn from those mistakes and fix them. While fixing the errors in life might be hard, fixing code is much easier and pretty straightforward.
Let's consider the problem and the provided code below. The illustration shows Edward's both initial and target states.
The code given below tries to move Edward to the final state. But can it do that? Press the "Run" button and see the output.
def turn_right():turn()def turn_around():turn()turn()def turn_left():turn()turn()turn()# Commands to complete the task.move()turn_right()move()move()turn_left()move()
The code did everything fine but forgot to remove the trash can. Although the code did not run into any errors, but the functionality it implemented was not what we desired. This type of error in the code's functionality is called a logical error.
Logical errors
Logical errors are subtle and challenging to detect. A logical error won’t prevent the code from executing, but the program produces unexpected results. The following example demonstrates a case of logical error in Python code:
def calculate_rectangle_area(length, width):area = 2*(length + width)return areaside_a = 5side_b = 8area_rect = calculate_rectangle_area(side_a, side_b)print("The area of the rectangle is: ", area_rect)
If you press the 'Run' button, it won't raise an error, but is the function working as expected?
The calculate_rectangle_area()
function written above implements an incorrect formula, and though it executes fine, the result is incorrect. The correct formula for the area of a rectangle is length * width
.