Recover from Errors

Let’s have a look at some common bugs and how to avoid them.

In this lesson, we’ll look at some of the common errors that we as programmers make and how to watch out for them. So, let’s begin!

Bugs

Following proper syntax and sequence is imperative while writing codes. But we all make mistakes, and it is not uncommon to run into errors while we code. The errors and flaws in code and its functionality are called bugs.

The two most common types of bugs are syntax errors and logical errors.

Syntax errors

Syntax errors occur when the code does not conform to the syntax rules of the programming language. These errors prevent the program from running. The code below provides an example of a syntax error in our code.

# Initialize a variable 'full_name' with an empty string
full_name = ""

# Prompt the user to enter their first name and store it in the 'first_name' variable
first_name = input("Enter your first name: )"

# Prompt the user to enter their last name and store it in the 'last_name' variable
last_name = input("Enter your last name: ")

# Concatenate the names with a space in between and store the result in 'my_name'
full_name = first_name + " " + last_name # The `+` symbol can be used to combine two strings.

# Display a message with the user's full name using the 'full_name' variable
print("My name is", full_name)
A code example with a syntax error

Note: The line number with the error in the output above is a bit misleading. Study the code line-by-line and identify the bug.

Find the bug

1.

Which line in the code has a syntax mistake?

A.

Line 7

B.

Line 11

C.

Line 5

D.

Line 2

E.

Line 8


1 / 1

If we fix the error, the code will run just fine.

Logical errors

These are more subtle and challenging to detect. Unlike syntax errors, 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 the code:

Python 3.10.4
def calculate_rectangle_area(length, width):
area = 2*(length + width)
return area
area_rect = calculate_rectangle_area(5, 8)
print("The area of the rectangle is: ", area_rect)

Here, we have used an incorrect formula and though it executes fine, the result is incorrect. The correct formula for the area of a rectangle is length * width.

Important points to consider

Here are some of the important points to consider:

Indentation in Python

  • In Python, indentation[object Object] is crucial for indicating the scope of code blocks as Python uses the level of indentation to determine the structure of the code.

  • The standard convention is to use four spaces for each level of indentation.

  • Consistent indentation is necessary for the code to be syntactically correct and for scoping to work as intended.

Try and run the code below:

Python 3.10.4
def calculate_rectangle_area(length, width):
area = length * width
return area
rect_area = calculate_rectangle_area(5, 8)
print("The area of the rectangle is: ", rect_area)

What's wrong with our code?

If we look closely enough, the return statement is not indented to be part of the calculate_rectangle_area function block. Therefore, when we try to return the area variable outside the function definition, it results in an error because area is not defined outside that scope.

  • Forgetting to indent code within a block can lead to indentation errors.

  • Indenting inconsistently within the same block can result in unexpected behavior.

  • Placing statements outside of the function when they should be inside can result in unexpected behavior.

The correct order of statements

  • Python executes statements sequentially within a block.

  • The correct order of statements is vital for the algorithm (or solution) of the program, or it may also result in a logical error.

# Initialize a variable 'full_name' with an empty string
full_name = ""

first_name = input("Enter your first name: ")

last_name = input("Enter your last name: ")

print("Hi there,", full_name)

# Concatenate the names with a space in between and store the result in 'my_name'
full_name = first_name + " " + last_name # The `+` symbol can be used to combine two strings.
The greeting program with logical error

The code seems to run fine, but the output is always empty. Can you figure out what is causing this bug?

Find the bug

1.

What is causing this logical error in this program?

A.

The full name resets at the end of the program.

B.

The name gets updated at the end of the program.

C.

The code displays the output before updating the full name.

D.

The concatenation syntax is not correct.


1 / 1

Changing the order of statements within the function can lead to logical errors.

The order of parameters and arguments in functions

  • Parameters are defined in the function signature.

  • Arguments are passed to the function when calling it, matching the order of parameters.

Python 3.10.4
def print_question(x, op, y):
print("What is the result of ", str(x), op, str(y), "?")
print_question(10, 2, "*")

The order in which we pass arguments to a function must match the order in which the parameters are defined in the function’s definition. Python uses positional arguments, meaning the value we pass for each argument is assigned to the corresponding parameter in the order they are listed.

In this function, x, op, and y are parameters, and they must be provided in that order when calling the function:

print_question(10, "*", 2)

Here, 10 corresponds to x, "*" corresponds to op, and 2 corresponds to y.

Changing the order does not work correctly, and we might get unexpected results or errors because the values are assigned to the parameters in the order in which they are listed in the function definition.

Let’s look at one more example:

Python 3.10.4
def calculate_sum(n1, n2, n3):
total = n1 + n2 + n3
return total
# Correct order of arguments
print(calculate_sum(3, 7, 2))
# Incorrect order of arguments (will result in an error)
print(calculate_sum(2, 5)) # This will raise a TypeError

In the code above:

The function calculate_sum expects three parameters (n1, n2, and n3), as is obvious from lines 1–3. The function call in line 6 results in the correct output. However, providing only two values (line 9) or swapping their order results in a TypeError because the function expects three arguments. So, the order, as well as the number of arguments, is essential for the function to work correctly.

  • Swapping the order of arguments can lead to logical errors.

  • Providing more or fewer arguments than the function expects can result in a TypeError.

Review of the lesson

To err is human. It’s important that when we encounter errors, we take the time to understand and learn from them. This can help us avoid similar issues in the future. By being careful, we can significantly reduce the occurrence of logical and syntax errors in our code. Our client will always expect a well-tested, bug-free app.