Designing, creating and refining algorithms
Common Errors in Code and How to Identify Them
Common Errors in Code and How to Identify Them Understanding common coding errors can help you debug and write more robust programs. Here are some typical errors and how to identify them:
Syntax Errors
Errors that occur when the code violates the grammatical rules of the programming language.
print("Hello World) # Missing closing quotation mark
Identification: The interpreter/compiler will usually point out the exact line and nature of the syntax error.
Runtime Errors
Errors that occur during the execution of a program.
result = 10 / 0 # Division by zero
Identification: The program will crash and typically produce an error message indicating the type of runtime error.
Logic Errors
Errors that occur when the code runs without crashing but produces incorrect results.
def add(a, b):
return a - b # Should be a + b
Identification: Often identified through testing and debugging when the output is not as expected.
Type Errors
Errors that occur when operations are performed on incompatible data types.
total = "sum" + 5 # Adding a string and an integer
Identification: python will raise a TypeError indicating the mismatch.
Name Errors
Errors that occur when the code refers to a variable that has not been defined.
print(variable) # variable is not defined
Identification: python will raise a NameError indicating the undefined variable.
Index Errors
Errors that occur when trying to access an index that is out of the range of a list.
my_list = [1, 2, 3]
print(my_list[5]) # Index out of range
Identification: python will raise an IndexError indicating the invalid index.
Key Errors
Errors that occur when trying to access a key that does not exist in a dictionary.
my_dict = {'a': 1, 'b': 2}
print(my_dict['c']) # Key 'c' does not exist
Identification: python will raise a KeyError indicating the missing key.
Dictionaries not used in GCSE
You don't need to know about dictionaries at GCSE.
Common Practices to Avoid Errors
- Use an IDE: Integrated Development Environments (IDEs) help identify syntax errors as you type.
- Debugging Tools: Use debugging tools and breakpoints to step through code and inspect variables.
- Create Test Tables: To test your expected outputs based upon inputs.
- Create Trace Tables: To debug and trace variable values to see where a program might be failing.
By understanding and identifying these common errors, you can debug your programs more effectively and write more reliable code.