Join the conversation
Types of Errors in Python:
SyntaxError, IndentationError, ArithmeticError, AssertionError, AttributeError, BufferError, EOFError, ImportError, ModuleNotFoundError, LookupError, IndexError, KeyError, MemoryError, NameError, UnboundLocalError,
OSError, FileNotFoundError, PermissionError, TimeoutError, ReferenceError, RuntimeError, NotImplementedError,
RecursionError, StopIteration, StopAsyncIteration, TypeError, ValueError, UnicodeError, UnicodeEncodeError,
UnicodeDecodeError, UnicodeTranslateError, ZeroDivisionError, EnvironmentError, FloatingPointError,OverflowError, GeneratorExit, SystemExit, SystemError, Warning, UserWarning, DeprecationWarning, PendingDeprecationWarning, SyntaxWarning, RuntimeWarning, FutureWarning, ImportWarning, UnicodeWarning,
BytesWarning, ResourceWarning.
Reply
Syntax Errors, Indentation Errors, Runtime Errors (Exceptions), ZeroDivisionError, IndexError, FileExistsError, AttributeError, FileNotFoundError, KeyError, TypeError (unhashable type), RecursionError (maximum recursion depth exceeded), MemoryError, Logical Error, ModuleNotFoundError, NameError, PermissionError
Reply
![](https://codanics.com/wp-content/uploads/2023/09/LIAQAT-PHOTO.jpeg)
In Python, errors are categorized into three main types: syntax errors, runtime errors, and logical errors. Here's a brief explanation of each:1 Syntax Errors:2 Runtime Errors:3 Logical Errors:
Reply
In Python, errors can be broadly categorized into three main types:1. **Syntax Errors:**
- Syntax errors, also known as parsing errors, occur when there is a mistake in the syntax of the code. These errors are detected by the Python interpreter during the parsing of the code.
- Example:```python
print("Hello, World!"
```In this case, there's a missing closing parenthesis, and running this code would result in a `SyntaxError`.2. **Runtime Errors (Exceptions):**
- Runtime errors, also called exceptions, occur during the execution of the program. They are not detected during the parsing phase but are encountered while the program is running.
- Example:```python
num1 = 10
num2 = 0
result = num1 / num2
```This code would raise a `ZeroDivisionError` because you cannot divide a number by zero.3. **Logical Errors:**
- Logical errors occur when the code is syntactically correct and runs without raising exceptions, but it does not produce the expected result due to a flaw in the algorithm or the logic.
- Example:```python
def add_numbers(a, b):
return a - b # Incorrect subtraction instead of additionresult = add_numbers(5, 3)
print(result)
```This code has a logical error because it subtracts `b` from `a` instead of adding them, leading to an incorrect result.Handling exceptions is a crucial aspect of writing robust and reliable Python code. You can use `try`, `except`, and other related constructs to catch and handle exceptions gracefully, preventing the program from crashing when encountering errors.
Reply
infinity
Reply
![](https://codanics.com/wp-content/uploads/2023/11/Weixin-Image_20230718222722-1.jpg)
#1.Syntax Errors:
#These occur when the Python interpreter encounters code that is not written according to the syntax rules. It often results from typos, missing colons, or incorrect indentation.
#Example:
#python
print("Hello, World"
#2.Indentation Errors:
# Indentation is significant in Python, and errors can occur if there are issues with the alignment of code blocks.
# Example:
# python
if True:
print("Indentation error")
#3.NameError
# This error occurs when a variable or name is used before it is defined.
# Example:
# python
print(x)
#4.TypeError:
# This error occurs when an operation or function is applied to an object of an inappropriate type.
# Example:
# python
result = "Hello" + 42
#5.ValueError:
# Raised when a function receives an argument of the correct type but an inappropriate value.
# Example:
# python
number = int("abc")
#6. IndexError:
# Raised when trying to access an element from a sequence (e.g., list, tuple) using an invalid index.
# Example:
# python
my_list = [1, 2, 3]
print(my_list[5])
#7. KeyError:
# Raised when trying to access a dictionary key that does not exist.
#Example:
# python
my_dict = {'a': 1, 'b': 2}
print(my_dict['c'])
#8. FileNotFoundError:
# Raised when attempting to open a file that does not exist.
# Example:
# python
with open('nonexistent_file.txt', 'r') as file:
content = file.read()
#9.ModuleNotFoundError:
# Raised when attempting to import a module that cannot be found.
# Example:
#python
import non_existent_module
#10.AttributeError:
# Raised when trying to access an attribute that doesn't exist.
# Example:
# python
my_list = [1, 2, 3]
my_list.append(4)
print(my_list.add(5)) # Should be print(my_list.append(5))
#11. ZeroDivisionError:
#Raised when attempting to divide a number by zero.
#Example:
#python
result = 10 / 0
#12. FileExistsError:
#Raised when trying to create a file or directory that already exists.
#Example:
#python
with open('existing_file.txt', 'x') as file:
file.write('Some content')
#13. PermissionError:
# Raised when trying to perform an operation that requires higher privileges, such as writing to a read-only file.
# Example:
#python
with open('/etc/some_file.txt', 'w') as file:
file.write('Content')
#14. ImportError:
#Raised when there is an issue with the import statement, such as when a module is not found or there is an error in the module being imported.
#Example:
#python
from non_existent_module import some_function
#15. TypeError (unsupported operand type):
#Raised when an unsupported operand type is used for an operation.
# Example:
#python
result = 'Hello' / 2
#16. TypeError (unhashable type):
#Raised when trying to use an unhashable type (e.g., a list) as a key in a dictionary.
#Example:
#python
my_dict = {['a']: 1}
#17. AttributeError (module has no attribute):
#Raised when trying to access an attribute that does not exist within a module.
#Example:
#python
import math
print(math.nonexistent_function())
#18. MemoryError:
# Raised when an operation runs out of memory.
#Example:
#python
data = [0] * 10**8 # Attempting to create a very large list
#19. TypeError (format string):
# Raised when there is an issue with the format string in functions like `format()`.
#Example:
#python
result = "The value is {}".format(42, 23)
#20. RecursionError (maximum recursion depth exceeded):
#Raised when a function exceeds the maximum recursion depth.
#Example:
#python
def infinite_recursion():
return infinite_recursion()infinite_recursion()
Reply
![](https://codanics.com/wp-content/uploads/2023/10/x8h6vl_1.jpg)
Thanks jazakumlah kharn ❤️
Reply
Assignment:
Syntax error: It occurs due to missed reserved keywords, spaces, quotes placed improperly.Name error: It occurs when variable, function or module doesn't exist.Type error: When the data type of object in inappropriate.Value error: when a function receives an argument with inappropriate value.Index error: It occurs when the value is accessed with values in list or tuple.Key error: It occurs when u accessed a key which is not exist.Attribute error: When you try to call an attribute whose type does not support that method.Zero division error: When a number is attempted to be divided by zero.File not found error: when you attempt to perform file operations like opening, reading, writing, or deleting a file.Import error: When you trying to import that module which does not exist.Memory Error: When your program runs out of memory.Timeout error: When the request could not be complete in a given time frame.
Reply
![](https://codanics.com/wp-content/uploads/2023/10/faisal-1.jpg)
Types of Errors in Python
Syntax Error
Occurs when the code violates Python language rules.
Example: print "Hello, world!"
Name Error
Occurs when the interpreter encounters a variable or function name that is not defined in the current scope.
Example: print(x)
Type Error
Occurs when you try to perform an operation on a variable or object of the wrong type.
Example: x = "Hello"; y = 5; print(x + y)
Value Error
Occurs when a built-in operation or function receives an argument that has the right type but an inappropriate value.
Example: int("abc")
Index Error
Occurs when you try to access an index that is out of range for a list or other sequence type.
Example: my_list = [1][2][3]; print(my_list[3])
Key Error
Occurs when a dictionary key is not found in the set of existing keys.
Example: my_dict = {"a": 1, "b": 2}; print(my_dict["c"])
Attribute Error
Occurs when you try to access an attribute of an object that does not exist.
Example: x = 5; print(x.length)
Zero Division Error
Occurs when you try to divide a number by zero.
Example: x = 5 / 0
File Not Found Error
Occurs when you try to open a file that does not exist.
Example: f = open("myfile.txt")
Import Error
Occurs when a module cannot be imported.
Example: import mymodule
Memory Error
Occurs when the program runs out of memory.
Example: x = * 1000000000
Timeout Error
Occurs when a function or operation takes too long to complete.
Example: import time; time.sleep(10)
Reply
done
Reply