When learning Python (programming language), you will encounter error messages. These are Pythonโs way of telling you that something is wrong with your code. Understanding them is important for debugging and fixing mistakes.
๐น 1๏ธโฃ SyntaxError
Occurs when Python cannot understand your code because it violates the rules of Python syntax.
Example:
print("Hello World"
Output:
SyntaxError: unexpected EOF while parsing
Fix: Ensure parentheses and quotation marks are properly closed.
๐น 2๏ธโฃ NameError
Occurs when you try to use a variable or function that has not been defined.
Example:
print(age)
Output:
NameError: name 'age' is not defined
Fix: Define the variable before using it:
age = 20
print(age)
๐น 3๏ธโฃ TypeError
Occurs when you perform an operation on incompatible types.
Example:
x = 5
y = "10"
print(x + y)
Output:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Fix: Convert types so they are compatible:
print(x + int(y))
๐น 4๏ธโฃ ValueError
Occurs when a function receives a valid type but invalid value.
Example:
num = int("hello")
Output:
ValueError: invalid literal for int() with base 10: 'hello'
Fix: Ensure the value can be converted properly:
num = int("123")
๐น 5๏ธโฃ IndexError
Occurs when you try to access an index that doesnโt exist in a list, tuple, or string.
Example:
fruits = ["apple", "banana"]
print(fruits[2])
Output:
IndexError: list index out of range
Fix: Check the length of the list before accessing elements.
๐น 6๏ธโฃ KeyError
Occurs when you try to access a key that doesnโt exist in a dictionary.
Example:
student = {"name": "Rahul", "age": 21}
print(student["grade"])
Output:
KeyError: 'grade'
Fix: Use a valid key or check with get():
print(student.get("grade", "Not Found"))
๐น 7๏ธโฃ AttributeError
Occurs when you try to use a method or attribute that doesnโt exist for a data type.
Example:
x = 5
x.append(3)
Output:
AttributeError: 'int' object has no attribute 'append'
Fix: Use the method on the correct data type:
nums = [5]
nums.append(3)
โญ Key Points
- Read error messages carefully, they tell you what and where the problem is.
- Common errors for beginners:
SyntaxError,NameError,TypeError,ValueError,IndexError,KeyError,AttributeError. - Debugging involves checking variable names, data types, and syntax.