10/22/24, 4:39 PM Unit1_7) Types_Of_Errors_While_working_with_python.
ipynb - Colab
add Code add Text
When working with Python, errors are a common occurrence, especially for beginners. Understanding the different
types of errors can help diagnose and fix issues quickly. Python errors are generally classified into the following
categories:
keyboard_arrow_down Syntax Errors
Definition: Occurs when Python’s syntax rules are violated.
Example: Forgetting a colon, parentheses, or an incorrect indentation.
if True # Missing colon
print("This will cause a syntax error.")
Cell In[1], line 1
if True # Missing colon
^
SyntaxError: expected ':'
if True: # Added colon
print("Now the code works.")
Now the code works.
keyboard_arrow_down Indentation Error
Definition: Python relies on indentation to define blocks of code. If indentation is incorrect or inconsistent, this error occurs.
Example: Misaligning code inside a loop, function, or conditional statement.
def greet():
print("Hello!") # IndentationError
greet()
Cell In[4], line 2
print("Hello!") # IndentationError
^
IndentationError: expected an indented block after function definition on line 1
def greet():
print("Hello!") # Fixed indentation
greet()
Hello!
keyboard_arrow_down Type Errors
Definition: Occurs when an operation is performed on incompatible data types.
Example: Trying to add a string to an integer.
number = 5
string = "10"
print(string)
print(type(string))
result = number + string # TypeError: unsupported operand
10
<class 'str'>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[10], line 5
3 print(string)
4 print(type(string))
----> 5 result = number + string # TypeError: unsupported operand
TypeError: unsupported operand type(s) for +: 'int' and 'str'
result = number + int(string) # Convert string to int
print(result)
print(string)
print(type(int(string)))
15
10
<class 'int'>
a=23.90
b=int(a)
print(a)
print(b)
23.9
23
keyboard_arrow_down Index Errors
Definition: Occurs when trying to access an index in a sequence (like a list or a tuple) that does not exist.
Example: Accessing an out-of-range index.
https://colab.research.google.com/drive/15fdrVW8Nbj5oUq0haLlYrNRKyilESlfS#printMode=true 1/3
10/22/24, 4:39 PM Unit1_7) Types_Of_Errors_While_working_with_python.ipynb - Colab
my_list = [1, 2, 3]
print(my_list[5]) # IndexError: list index out of range
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Cell In[8], line 2
1 my_list = [1, 2, 3]
----> 2 print(my_list[5]) # IndexError: list index out of range
IndexError: list index out of range
keyboard_arrow_down Key error
Definition: Happens when trying to access a key in a dictionary that does not exist.
Example: Accessing a missing key.
my_dict = {'name': 'Alice'}
print(my_dict['age']) # KeyError: 'age'
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[9], line 2
1 my_dict = {'name': 'Alice'}
----> 2 print(my_dict['age']) # KeyError: 'age'
KeyError: 'age'
print(my_dict.get('age', 'Key not found')) # Avoids KeyError
Key not found
keyboard_arrow_down Attribute Error
Definition: Occurs when trying to access or call a method or attribute that does not exist for an object.
Example: Calling a method that isn’t defined for a particular data type.
number = 10
number.append(5) # AttributeError: 'int' object has no attribute 'append'
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[11], line 2
1 number = 10
----> 2 number.append(5) # AttributeError: 'int' object has no attribute 'append'
AttributeError: 'int' object has no attribute 'append'
my_list = [10]
my_list.append(5) # Now it works since lists have an append method
[10, 5]
keyboard_arrow_down Value Error
Definition: Raised when a function gets an argument of the correct type but with an inappropriate value.
Example: Passing a string that cannot be converted to an integer.
int_value = int('abc') # ValueError: invalid literal for int() with base 10
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[14], line 1
----> 1 int_value = int('abc') # ValueError: invalid literal for int() with base 10
ValueError: invalid literal for int() with base 10: 'abc'
int_value = int('123') # Now it works
keyboard_arrow_down Zero Division Error
Definition: Occurs when attempting to divide a number by zero.
Example: Dividing by zero.
result = 10 / 0 # ZeroDivisionError: division by zero
result
https://colab.research.google.com/drive/15fdrVW8Nbj5oUq0haLlYrNRKyilESlfS#printMode=true 2/3
10/22/24, 4:39 PM Unit1_7) Types_Of_Errors_While_working_with_python.ipynb - Colab
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Cell In[16], line 1
----> 1 result = 10 / 0 # ZeroDivisionError: division by zero
2 result
ZeroDivisionError: division by zero
divisor = 0
if divisor != 0:
result = 10 / divisor
else:
print("Cannot divide by zero")
Cannot divide by zero
keyboard_arrow_down Import Errors
Definition: Occurs when trying to import a module that does not exist or is not installed.
Example: Importing a nonexistent module.
import my_nonexistent_module # ImportError: No module named 'my_nonexistent_module'
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Cell In[18], line 1
----> 1 import my_nonexistent_module # ImportError: No module named 'my_nonexistent_module'
ModuleNotFoundError: No module named 'my_nonexistent_module'
keyboard_arrow_down File Error
Definition: Occurs when trying to access or manipulate a file that doesn’t exist or cannot be opened.
Example: Trying to open a non-existent file.
with open('non_existent_file.txt', 'r') as file:
content = file.read() # FileNotFoundError
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Cell In[19], line 1
----> 1 with open('non_existent_file.txt', 'r') as file:
2 content = file.read() # FileNotFoundError
File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\IPython\core\interactiveshell.py:324, in _modified_open(file, *args, **kwargs)
317 if file in {0, 1, 2}:
318 raise ValueError(
319 f"IPython won't let you open fd={file} by default "
320 "as it is likely to crash IPython. If you know what you are doing, "
321 "you can use builtins' open."
322 )
--> 324 return io_open(file, *args, **kwargs)
FileNotFoundError: [Errno 2] No such file or directory: 'non_existent_file.txt'
import os
if os.path.exists('file.txt'):
with open('file.txt', 'r') as file:
content = file.read()
else:
print("File not found")
File not found
Start coding or generate with AI.
https://colab.research.google.com/drive/15fdrVW8Nbj5oUq0haLlYrNRKyilESlfS#printMode=true 3/3