Python Error Types
Types of Errors in Python
Syntax Error
Definition: Occurs when Python encounters code that violates its syntax rules.
Example: print("Hello World)
Explanation: The closing quote is missing, which violates Python’s syntax rules.
Indentation Error
Definition: Occurs when the code is not properly indented, breaking Python’s strict indentation rules for blocks.
Example: for i in range(5): print(i)
Explanation: The print statement should be indented under the for loop.
Name Error
Definition: Happens when a variable or function is used before it is defined.
Example: print(my_variable)
Explanation: my_variable is not defined before it is used.
Type Error
Definition: Raised when an operation is performed on incompatible data types.
Example: result = 5 + "10"
Explanation: Cannot add an integer (5) and a string ("10").
Attribute Error
Definition: Occurs when a non-existent attribute is accessed on an object.
Example: text = "Hello" text.append(" World")
Explanation: Strings do not have an append() method.
Value Error
Definition: Happens when a function receives an argument of the correct type but an inappropriate value.
Example: number = int("Hello")
Explanation: The string "Hello" cannot be converted to an integer.
Index Error
Definition: Occurs when trying to access an element of a list or tuple that is out of range.
Example: my_list = [1, 2, 3] print(my_list[3])
Explanation: The list has only three elements (indices 0, 1, and 2).
Import Error
Definition: Occurs when an imported module cannot be found or cannot be loaded.
Example: import non_existent_module
Explanation: The specified module does not exist.