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.

Python 3.10.4
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:

Python 3.10.4
def calculate_rectangle_area(length, width):
area = 2*(length + width)
return area
side_a = 5
side_b = 8
area_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.

The order of parameters and arguments in functions

This is another common logical error: we mistakenly pass arguments to functions in an incorrect order. 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.

Recall:

Parameters are defined in the function definition, while arguments are passed to the function when calling it, matching the order of parameters.

Example

Often, products in supermarkets are sold in packs. Suppose we want to write a function that calculates the price of a single item from a pack. Given the total price of one pack is 300 and the total number of items in the pack is 15, our program should help find the price of a single item.

Python 3.10.4
def price_per_item(total_price, no_of_items):
item_price = total_price / no_of_items
return item_price
# Incorrect usage (arguments are swapped)
price = price_per_item(15, 300)
print(price)

The parameters total_price and no_of_items should be provided in the function call in the same order as they were in the function definition. Changing the order while calling the function produces unexpected results.

Errors known to Python

Although logical errors are somewhat hard to detect, luckily for us, not all the errors in Python are hidden, and are thus detected at compile time. When we press the "Run" button on our Python compiler and it outputs an error, it is trying to communicate that it is having trouble understanding the code. Remember, communication is the key, and we should pay due attention to what Python is trying to tell us to solve the problems.

Let's try running the erroneous code below and see how Python responds to it.

Python 3.10.4
print("Hello Python!"

From the last line of Python's response, we see that it is telling us about the error. We forgot to close the parentheses! We can fix this error by fixing what is causing the trouble, i.e., closing the parentheses.

Notice that Python associated a type, "SyntaxError". There are more types of errors in Python. In this lesson, we will explore some common types of errors that beginners run into while learning Python.

Syntax errors

Every programming language has a specific grammar that must be followed. This unique grammar is known as the syntax of the programming language. A syntax error occurs when the code does not conform to the code-writing conventions or rules set by the programming language. Code with syntax errors will stop during runtime.

The syntax in Python is one of the easier ones in the world of coding. While we will learn new syntax conventions as we proceed with the course, let's have a look at some simple syntax problems to get an idea of what they are and the sort of trouble they can cause.

Below is another common syntax mistake that new users tend to make. Can you spot where the issue is? If you need a hint, asking the AI mentor is a good idea.

Python 3.10.4
# Function definition
def sum_three_numbers(a, b, c)
value = a + b + c
return value
# Function call
answer = sum_three_numbers(4, 5, 6)
# Displaying the result
print(answer)

Indentation error

The code in Python uses indentation styling to define the scope of programming elements. For example, when writing a function, every thing that is indented after the declaration is a part of the function and lies in the scope of that function.

Try running the code below and observe the output. See if you can figure out what Python is trying to tell us.

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)

The standard convention is to use four spaces for each level of indentation, but it is not a necessity. What's necessary is to be consistent while indenting. For example, if you indent a line of code by four spaces and the next line by two, the two lines will exist inside a different scope and may cause an error.

This is demonstrated in the code below. Try running it and observe the output.

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)

The error occurred due to inconsistent indentation in the code. There are a couple of ways to fix this error:

  • Adding two spaces of indentation in line 2.

  • Removing two spaces of indentation from line 3.

Remember, we want to be consistent while indenting. The choice is your's or your IDEIntegrated Development Environment. Basically the software that you choose to write your code with.'s at the end of the day.

Type error

Another type of error that's worth mentioning at this point is the type error. We have already seen the type error once when we tried to add up different types together. A string cannot add up with a number, and hence we run into an error.

Python 3.10.4
answer = 5 + "2"
print(answer)

Trying to use arithmetic operators with unsupported data types is one way a type error can occur. More generally, a type error is raised to indicate that the type of an operand or argument is not supported for the intended operation. Let's have a look at some common scenarios where it can show up.

Function arguments of the wrong type

Python 3.10.4
len("John")
len(42)

The len() function can work with strings but gives an error with an integer. So, the first line of code executed fine but the second line raised an error.

Calling an object that isn't callable

Python 3.10.4
number = 42
result = number()

Here, number is an integer and not a callable object (like a function), so trying to call it as if it were a function raises a type error.

Incorrect number of parameters in a function call

Python 3.10.4
# Function definition
def sum_three_numbers(a, b, c):
value = a + b + c
return value
# Function call
answer = sum_three_numbers(4, 5)
# Displaying the result
print(answer)

Using a different number of parameters than what is supported by a function can also cause a type error. The sum_three_numbers() requires three parameters, but in line 7, we only provided it with two, and Python raised an error.

Recap

There are problems (errors) we can run into while coding, but like all other problems, the problems in code have a solution. While Python can help us identify most of the problems through its communicative error messages, there are certain problems we have to solve on our own. As we advance into our programming journey, we will become better and better at identifying and fixing those errors ourselves.

Key takeaways:

Errors known to Python

There are some kind of errors that can be detected by Python during code execution. Python raises messages to explain these errors. Some common detectable errors that can occur while coding are:

  1. Syntax errors: Errors that occur when we miss a syntax element required by the language. For example, missing a parenthesis while calling a function or incorrect order of variable assignment.

  2. Indentation errors: Python uses indentation to define the scope of its code portions. Incorrect syntax can disrupt the logical structure and flow of the code and is often detected by Python.

  3. Type errors: Python raises a type error when an operation or function is applied to an object of inappropriate type. For example, trying to call a variable using parenthesis or trying to add a number to text.

Errors unknown to Python

There are some errors that can cause our code to demonstrate incorrect behavior but are not detected during code execution. These errors are known as logical errors and need to be figured out by the coders themselves.