Python

Error Types in Python

Coders, especially novice coders, tend to encounter errors. An error in the code prevents the code from fully running properly or in the intended manner. In particular, the errors thrown by Python falls into one of three categories: syntax errors, runtime errors or logical errors. In this tutorial, we will be learning the different types of errors that Python can throw.

Syntax Errors

A syntax error or a parsing error is a type of error that is thrown when Python doesn’t quite understand what you’re trying to say. We need to communicate to the Python interpreter what we want to say much like the spoken language. For example, you may wish to say Happy Birthday to your friend. But if you botch up the word Happy and instead forget to write the H and the y, then the word is misunderstood or even worse, it cannot be worked out. In the same manner, Python comes with a set of very rigid rules, and words. When you break the rules or write the words with an error in it, the Python interpreter simply cannot understand what you’re trying to say, and it’ll throw a syntax error. This error can simply be fixed by reviewing the syntax and fixing it so that it does indeed abide by the rule set by Python.

Example #1: forgotten syntax

main.py

name = "what is your name? "

if name != "Linux"
    print("hello %s" % name)

Output:

File "C:\Users\kalya\PycharmProjects\pythonProject\main.py", line 3
    if name != "Linux"
                      ^
SyntaxError: expected ':'

Process finished with exit code 1

This is by far is the simplest example of a syntax error. The rules of Python state that there needs to be a colon at the end of the if statement, and here we’ve simply omitted it. That alone has screwed up Python – it doesn’t understand what you’re asking it to do. So, the simple fix is to add a colon at the end of the if statement. And oddly enough, it will tell you what is wrong and how to fix it. In this case, it says “expected :”. So, it’s telling you that it hopes for a colon there.

Example #2: wrong syntax

main.py

for i im range(5):
print(i)

Output:

File "C:\Users\kalya\PycharmProjects\pythonProject\main.py", line 1
    for i im range(5):
          ^^
SyntaxError: invalid syntax

Process finished with exit code 1

Here, I wrote im instead of in. So, it threw a syntax error because the word used is wrong. In Python, a set of words are special words, and they already have pee-defined meanings. When you use a word that is not within that set, it doesn’t recognize it and goes huh?

Example #3: missing or wrong brackets

main.py

dictionary = ['Jim':24, 'Jenny':23, 'Jack':30]

print(dictionary)

Output:

File "C:\Users\kalya\PycharmProjects\pythonProject\main.py", line 1
    dictionary = ['Jim':24, 'Jenny':23, 'Jack':30]
                       ^
SyntaxError: invalid syntax

Process finished with exit code 1

In this case, we’re tying to use a dictionary in Python. But we didn’t use the curly braces and instead used the square braces which lead to an error. According to the rules, in Python, for a dictionary, we use curly braces.

Runtime Errors

You might get an error even if you didn’t make any syntax errors. When the error occurs during the execution of the code, it is also known as an exception or a runtime error. So, you begin writing the code, and it begins executing without any problems. But midway, it just stops and says that there’s an error – this is called an exception.

Example #1: Attempting to divide a string by an integer

main.py

name = 'LinuxHint'
age = 24

total = name / age
print (total)

Output:

File "C:\Users\kalya\PycharmProjects\pythonProject\main.py", line 4, in <module>
    total = name / age

TypeError: unsupported operand type(s) for /: 'str' and 'int'

Process finished with exit code 1

Here, we are attempting to divide a string by an integer, and that’s called an exception or a runtime error.

Example #2: Trying to access a file that does not exist

main.py

f = open('file.txt', 'r')

print(f.read())

Output:

File "C:\Users\kalya\PycharmProjects\pythonProject\main.py", line 1, in <module>
f = open('file.txt', 'r')

FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'

Process finished with exit code 1

In this instance, we’re pointing to a file that does not exist. So, the program runs but terminates early with a runtime error message because it can’t locate that file.

Logical Errors

Unlike a syntax error or a runtime error, the logical error is a lot harder to pinpoint. It is also a lot harder to deal with. So, Python won’t crash, and it won’t display any error messages either. In this case, the program will run, and it will give us a result. But the result will be incorrect. So, where’s the mistake? In the programmer’s logic.

Example #1: Logical error

main.py

x=5
y=6

z = x+y/2

print("The average of %f and %f is %f" % (x, y , z))

Output:

The average of 5.000000 and 6.000000 is 8.000000

Process finished with exit code 0

Here, the average of 5 and 6 is not 8! So here the code is executed and chucked out a result. But the beginner would sit there and scratch his head because the results are wrong.

Example #2: Logical error

main.py

dictionary = {'Jim':24, 'Jack':45, 'John':60}

for member in dictionary:
    age = dictionary[member]
    if age < 40:
        print("you are 40 years old or older. You may enter this site.")
    else:
        print("You are too young to enter this site")

Output:

you are 40 years old or older. You may enter this site.
You are too young to enter this site
You are too young to enter this site

Process finished with exit code 0

The reason for this code is to exclude those who are under 40 from the website. But as you might have noticed, the programmer put a less than sign instead of a greater than sign after age (age <40). Both Jack and John are older than 40 but the program says that they are too young to enter this site. Jim who is 24 is allowed because it thinks that he’s older than 40. This is a logical problem. It can be solved by changing the greater than/less than sign.

In Python, all the errors you’re going to get can be categorized into three groups: syntax, runtime/exception, or logical errors. Both the syntax and the runtime error will cause Python to crash. It will typically display a message letting you know how to fix the problem and where the problem is. This is not the case for a logical error. A logical error doesn’t cause Python to crash, but rather chucks out results that are completely and utterly wrong. So, of the three, logical errors are the hardest to deal with because we don’t know where the error is located.

About the author

Kalyani Rajalingham

I'm a linux and code lover.