The common errors in Python
1.SyntaxError: Invalid Syntax
Scenario: You’re writing a simple Python program, but you accidentally miss a parenthesis
def greet(name):
print(“Hello, “ + name) # SyntaxError: expected an indented block
Fix:Properly indent the code block.
def greet(name):
print(“Hello, “ + name)
2. IndentationError: Unexpected Indent
Scenario: You forgot to indent a line correctly within a function or control structure.
def add_numbers(a, b):
return a + b
Fix:Use proper indentation to define the block inside the function.
def add_numbers(a, b):
return a + b
3. TypeError: Unsupported Operand Type(s)
Scenario: You try to combine incompatible types, like a string and an integer.
a = “Hello”
b = 5
print(a + b)
Fix:Convert the integer to a string before concatenation.
print(a + str(b))
4. NameError: Name Not Defined
Scenario: You reference a variable that has not been defined in your code yet.
print(x)
Fix:Declare and initialize x
before referencing it
x = 10
print(x)
5. IndexError: List Index Out of Range
Scenario: You attempt to access an index that doesn’t exist in a list.
my_list = [1, 2, 3]
print(my_list[5])
Fix:Ensure the index is within the valid range.
if len(my_list) > 5:
print(my_list[5])
else:
print(“Index out of range”)
6. ValueError: Invalid Value
Scenario: You’re trying to convert a string into a number, but the string can’t be interpreted as a valid number.
value = int(“Hello”)
Fix:Handle the conversion properly or use try-except
to catch errors.
try:
value = int(“123“)
except ValueError:
print(“Invalid value for conversion.“)
7. KeyError: Key Not Found in Dictionary
Scenario: You try to access a key in a dictionary that doesn’t exist.
my_dict = {‘name‘: ‘Alice‘, ‘age‘: 30}
print(my_dict[‘address’])
Fix:Use .get()
to avoid an exception when the key is not found.
print(my_dict.get(‘address‘, ‘Key not found‘))
8. AttributeError: Object Does Not Have the Method
Scenario: You try to use a method that doesn’t exist for a particular type of object.
“hello“.append(” world”)
Fix: Use string concatenation or other string methods.
“hello” += ” world”
9. ZeroDivisionError: Division by Zero
Scenario: You try to divide a number by zero
result = 10 / 0
Fix: Check if the denominator is zero before performing division.
denominator = 0
if denominator != 0:
result = 10 / denominator
else:
print(“Cannot divide by zero”)
10. FileNotFoundError: File Doesn’t Exist
Scenario: You attempt to open a file that doesn’t exist on the system.
with open(‘non_existent_file.txt’, ‘r’) as file:
content = file.read()
Fix:Ensure the file exists or use a try-except
block to handle the error.
try:
with open(‘non_existent_file.txt’, ‘r’) as file:
content = file.read()
except FileNotFoundError:
print(“File not found.“)
Resources:
- Python Official Documentation: https://docs.python.org/3/
- Real Python: https://realpython.com/
- GeeksforGeeks: https://www.geeksforgeeks.org/python-exceptions/