Identify and Debug errors easily in Python

timiemmy

Faith Bolanle

Posted on September 16, 2023

Identify and Debug errors easily in Python

Errors in a program are inevitable. You can't but encounter a mistake as you code.

Errors in programming, also known as bugs, occur when there is a code mistake or when the regulation violates the prescribed usage. Errors can also occur when a user on the other hand acts different from what the program is programmed to do.

Types Of Errors

In Python, the errors you encounter can be classified into three categories which are:

  1. Syntax Errors

  2. Logic Error

  3. Runtime Error

Let's take these errors one after the other.

1. Syntax Errors

Just like every human language has a syntax formula for how the words must be arranged for better communication and understanding, Each programming language also has its rules on how a code must be written. Read more on Python syntax.

Syntax errors are inevitable. It is the error most beginners face when starting as a programmer. You will encounter syntax errors more than other errors in your code due to some mistakes while typing in your code.

Few reasons why a syntax error is raised:

You use number or Python built-in function names as variable names.

You missed or misplaced punctuations. for example, commas, parentheses, colons, quotes, and all.

You indented incorrectly in your code.

File 'helloworld.py', line 5
    print("Hello, world!'
                        ^
SyntaxError: EOL while scanning string literal
Enter fullscreen mode Exit fullscreen mode

Here, the error is raised because there are no closing parentheses. Note that it tells you the exact place the error is coming from by including the line.

Indentation Error

if welcome = "hello_world":
    print(welcome)
    ^
IndentationError: unexpected indent
Enter fullscreen mode Exit fullscreen mode

Here an error is raised because it is not indented correctly.

Note: Sometimes you don't see this indented error in your code, the problem is, that you use a combination of space bar and tab for indenting. Your indentation must be consistent.

2. Logic Errors

A logic error is an error that occurs even though there is no error in your code. What makes it an error then? it is an error because it gives the wrong output. A logic error is sometimes not noticed because it is not raised by the code editor but it can do damage to your code while running it.

Examples of Logic Error

Off-by-one error

#error in a for loop
for i in range(1, 5): # To include 5, you need to add 6 or 5+1
    print(i)

# Output
1
2
3
4
Enter fullscreen mode Exit fullscreen mode

Infinite Loop

while True:
    print("This loop will run forever!")
Enter fullscreen mode Exit fullscreen mode

This loop will keep running because it has no condition to stop it.

Incorrect operation

a = 20
b = 40
c = a * b  # Incorrect operation

print("Adding", a, "and", b, "=", c)

# Output: Adding a and b = 800
# Instead of: Adding a and b = 60
Enter fullscreen mode Exit fullscreen mode

3. Runtime Errors

A runtime error, similar to a logic error is an error that occurs when your code is running. A runtime error, when detected in your program will terminate the program. To help you understand better, the following are examples of runtime errors.

Zero Division error

This type of runtime error is raised when you try to divide a number by zero which is impossible. Can you do that ordinarily in mathematics? 🙄

# Input
print(10/0)

# Output
File "file.py", line 1
  print(10/0)
ZeroDivisionError: division by zero
Enter fullscreen mode Exit fullscreen mode

This is to let you know you can't divide a number by zero.

NameError

Your code will raise this type of error if you try to access an undefined variable or function name.

# Input
y = 20

# Output
Traceback (most recent call last):
  File "file.py", line 1, in <module>
    print(x)
NameError: name 'x' is not defined
Enter fullscreen mode Exit fullscreen mode

The error says that the x is defined as neither a variable nor a function, and it tells you where to check by including the line.

Type Error

This error will always occur when you try to operate on two different data types that are not compatible.

# Input
print(5 + 'have you subscribed to my newsletter?')

# Output
File "file.py", line 1, in <module>
    print(5 + 'have you subscribed to my newsletter?')
TypeError: can only concatenate str (not "int") to str
Enter fullscreen mode Exit fullscreen mode

Index Error

# Input
numbers = ["Don't", "forget", "to", "subscribe", "to my newsletter"]
print(numbers[5])

# Output
Traceback (most recent call last):
  File "file.py", line 2, in <module>
    print(numbers[5])
IndexError: list index out of range
Enter fullscreen mode Exit fullscreen mode

Indexing in Python starts from zero(0), trying to access an index of 5 will return an index error.

FileNotFound Error

This error is raised when you try to access a file which does not exist in read mode. If it is in write mode, it could create the file but in read mode, it will raise an error.

# Input
with open("like.txt", "r")

# Output
Traceback (most recent call last):
  File "file.py", line 1, in <module>
    with open("like.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'like.txt'
Enter fullscreen mode Exit fullscreen mode

How To Solve The Errors

  1. Find the error: The first step in solving an error is to find it. You can do this by reading the error message that appears when you run your code. The error message will usually tell you what went wrong and where it happened in your code.

  2. Understand the error: Once you've identified the mistake, you need to understand why it occurred, which could be typographical, logical, or mathematical. This might involve looking up information about the Python library, the module, or the file you're using or going through your code line by line to find the error.

  3. Fix the error: Once you know what caused the error, you can fix it. This might mean changing your code to correct the error or trying a different approach to solve the problem.

  4. Test the code: After you've fixed the mistake, it's important to test your code to make sure it works correctly. You can do this by running your code and checking the output or using a tool specifically designed for testing your code.

Conclusion

In programming, errors are an inevitable part of the process. As a Python developer, understanding the types of errors that can occur is crucial for writing good and reliable code. Throughout this article, we explored three main categories of errors: Syntax Errors, Logic Errors, and Runtime Errors.

Remember, as a developer, having errors in your code is a natural part of the learning and coding journey. Errors offer great growth opportunities, as they provide insights into areas that need improvement and help sharpen your debugging skills. So, embrace the errors, learn from them, and keep coding with confidence!😎💻

💖 💪 🙅 🚩
timiemmy
Faith Bolanle

Posted on September 16, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related