if True
print("Hello World")
SyntaxError: expected ':' (975521850.py, line 1)
When an error arises, there will be an error message with the type of error and the line the error occured on. This notebook goes over how to handle the common types of errors and exceptions in Python.
I recommend looking at the Python tutorial page for more information on errors. Searching for the error message directly on Google can help the debugging process if there is an error not discussed in this page.
A SyntaxError occurs when the syntax of your code is incorrect.
A colon is expected after the if
statement, which arises the syntax error. The error goes away after adding the colon.
A NameError occurs when a variable, function, or module used does not exist. When this happens, it is usually because of a spelling error.
A TypeError occurs when you input an incorrect data type for an operation or function.
In python, you cannot add strings to integers. You can add, however, an integer to an integer or a string to a string with a +
.
A ZeroDivisionError occurs when you try to divide by zero. To fix this, recheck your computation.
A ValueError occurs when an input for a function is the correct data type but is invalid in regards to the domain of the function. This is most common with mathematical operations.
In the example above, you must input a positive number into the sqrt()
function. The negative number is still an integer, but it is not in the function’s domain.
An IndexError occurs when you try to access an item in a list with an index out of bounds.
The range of a list is [0, n-1], where “n” is the length of the list. So, the list [1,2,3,4,5]
has index elements in the range 0-4.
A ModuleNotFoundError occurs when you try to import a module that does not exist. It is a type of ImportError. To fix this error, check if you have installed the module in your python environment from the terminal command-line.
You can use a try
statement to catch errors. A try
clause includes the code you want to run that might cause an error. If no error occurs, the try
clause runs successfully. If an error does occur, the except
clause runs after the line in the try
clause that caused an error.
The except
clause above can catch any type of error. However, an except
clause can also catch a specific type of error. There can be mulptile except
clauses in a try
statement to catch the different types of errors.
These are not all the errors that might come up in your coding. If another type of error occurs, you can search the error type on Google to learn more about what has caused it. As always, remember to look at the line resulting in the error for hints on what could have gone wrong!