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.