fbpx

Errors

What are errors?

By now, you have certainly encountered many errors throughout your Python programs. This is a part of learning any new programming language, and being able to debug your errors as they occur is an extremely valuable skill to have. In order to effectively debug our code, it helps to have an understanding of the three main categories of errors that might occur:

  1. Syntax errors occur when the interpreter encounters code that doesn’t conform to the language’s syntax rules. These errors are usually detected by the interpreter before the program is executed.

  2. Runtime errors occur when the program is syntactically and logically correct, but an error occurs during the execution of the program. These errors are typically caused by unexpected conditions or incorrect input.

  3. Logic errors occur when the code runs without any syntax errors, but the program doesn’t produce the expected output or behavior. These errors are caused by mistakes in the algorithm or the program’s logical flow.

When an error occurs, Python will usually print an error message that describes the problem. The error message will include the type of error, a traceback (which shows the sequence of function calls that led to the error), and the line number where the error occurred.

Syntax Errors

Syntax errors occur when the interpreter encounters code that does not conform to the language’s syntax rules. Here are a few examples of common syntax errors in Python:

Missing colon: A colon is required after certain statements such as if, else, for, and while. If you forget to include the colon, you’ll get a syntax error. For example

				
					# Incorrect syntax
if x > 5
    print("x is greater than 5")

# Correct syntax
if x > 5:
    print("x is greater than 5")

				
			

Incorrect indentation: In Python, indentation is used to group statements. If you have an incorrect indentation, you’ll get a syntax error. For example:

				
					# Incorrect syntax
def my_function():
print("Hello, world!")

# Correct syntax
def my_function():
    print("Hello, world!")

				
			

Missing or mismatched parentheses, brackets, or quotes: When using parentheses, brackets, or quotes, you need to make sure they’re properly closed or opened. For example:

				
					# Incorrect syntax
my_list = [1, 2, 3
print(my_list)

# Correct syntax
my_list = [1, 2, 3]
print(my_list)

				
			

Incorrect variable names: Variable names cannot start with a number or contain special characters. If you use an incorrect variable name, you’ll get a syntax error. For example:

				
					# Incorrect syntax
1variable = 5

# Correct syntax
variable1 = 5

				
			

Runtime Errors

Runtime errors occur when the program is syntactically and logically correct, but an error occurs during the execution of the program. Runtime errors are also called “exceptions” and are typically caused by unexpected conditions or incorrect input. Here are a few examples of common runtime errors in Python:

ZeroDivisionError: This error occurs when you try to divide a number by zero.

				
					x = 5
y = 0
result = x / y
# This will raise a ZeroDivisionError

				
			
NameError: This error occurs when you try to use a variable or function that hasn’t been defined yet. For example:
				
					# if I try to print age before it has been defined, it will give me a NameError
print(age)

age = 18


				
			

TypeError: This error occurs when you try to use an object of the wrong type, such as trying to divide a string by an integer. For example:

				
					x = "5"
y = 2
result = x / y
# This will raise a TypeError since you cannot divide a string by a number

				
			

IndexError: This error occurs when you try to access an element of a list or tuple that doesn’t exist. For example:

				
					fruits = ["apples", "oranges", "bananas"]
print(fruits[3])
# This will raise an IndexError since we can only index from 0 to 2


				
			

ValueError: This error occurs when a function or method receives an argument of the correct type but an invalid value. For example:

				
					int("hello")
# This will raise a ValueError since "hello" cannot be converted to an integer

				
			

These are just a few examples of runtime errors that we may encounter in our code. To see a full list of runtime errors (also commonly known as exceptions), you can try typing the following into your code:

				
					print(dir(locals()['__builtins__']))

# this will display all possible exceptions you might see in your code:

# ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

				
			

Our next topic, exception handling, will show us how we can avoid runtime errors and choose to handle them a different way besides printing out the error message to the console.

Logic Errors

Logic errors occur when the code runs without any syntax errors, but the program doesn’t produce the expected output or behavior. Logic errors are also called “bugs” and are typically caused by mistakes in the algorithm or the program’s logical flow. These are also typically the most difficult to debug, since they do not raise any error or exception at all. It forces the program to pick through their code to determine where they might have made a mistake in their logic. 

Some examples of logic errors might be:

  • Printing out 6 when I meant to print 7
  • Telling me “good morning” when you meant to say “good afternoon”
  • Displaying the first item in a list when I meant to display the second

Again, logic errors do not actually describe what your error is, so it requires the programming to retrace through their code to debug it.

Replit Practice

Loading...