Python is an easy-to-learn and use programming language. However, Python is prone to errors like any other programming language.
In this article, I would be discussing the common types of errors a Python programmer is likely to encounter and how to handle them.
Errors are problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which change the normal flow of the program.
Two types of Error occurs in Python:
- Syntax Errors
- Logical Errors (Exceptions)
Syntax Errors In Python
Syntax errors occur when you have a typo or other mistake in your code that causes it to be invalid syntax. These errors are usually caught by Python's interpreter when you try to run the code.
Example:
#python
if x = 10:
print('x is equal to 10')
Output:
Cell In[12], line 1
if x = 10:
^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
In this example, we are trying to assign the value 10 to the variable x using the assignment operator (=) inside an if statement.
But the correct syntax for comparing values in an if statement is to use the comparison operator (==).
So here's how you fix this one:
#python
if x == 10:
print('x is equal to 10')
Here are some tips for avoiding syntax errors:
- Double-check your code for typos or other mistakes before running it.
- Use a code editor that supports syntax highlighting to help you catch syntax errors.
- Read the error message carefully to determine the location of the error.
Logical Errors In Python (Exceptions)
When in the runtime an error that occurs after passing the syntax test is called exception or logical type. For example, when we divide any number by zero then the ZeroDivisionError exception is raised, or when we import a module that does not exist then ImportError is raised.
A few of the errors would be discussed below, how they are caused and how they can be fixed.
Indentation Error In Python:
One of the most common errors in Python is indentation errors. Unlike many other programming languages, Python uses whitespace to indicate blocks of code, so proper indentation is critical.
To avoid indentation errors, it's a good idea to use a code editor that supports automatic indentation, such as PyCharm or Visual Studio Code.
Example:
#python
for i in range(10):
print(i)
In this example, the code inside the for loop is not indented correctly.
Fix:
#python
for i in range(10):
print(i)
Name Errors In Python:
Name errors occur when you try to use a variable or function that hasn't been defined. For example, if you try to print the value of a variable that hasn't been assigned a value yet, you'll get a name error.
Example:
#python
my_variable = 5
print(my_vairable)
In this example, we misspelled the variable name my_variable as my_vairable.
Fix:
#python
my_variable = 5
print(my_variable)
Type Errors In Python:
Another common error in Python is type errors. Type errors occur when you try to perform an operation on data of the wrong type. For example, you might try to add a string and a number, or you might try to access an attribute of an object that doesn't exist.
Example:
#python
x = "5"
y = 10
result = x + y
In this example, we are trying to concatenate a string and an integer, which is not possible.
Fix:
#python
x = "5"
y = 10
result = int(x) + y
Here, we convert the string to an integer using the int() function before performing the addition.
Index Errors In Python:
Index errors occur when you try to access an item in a list or other sequence using an index that is out of range. For example, if you try to access the fifth item in a list that only has four items, you'll get an index error.
Example:
#python
my_list = [1, 2, 3, 4]
print(my_list[5])
In this example, we are trying to access an item at index 5, which is outside the range of the list.
Fix:
#python
my_list = [1, 2, 3, 4]
print(my_list[3])
Here, we access the item at index 3, which is within the range of the list.
Key Errors In Python:
Key errors occur when you try to access a dictionary using a key that doesn't exist. For example, if you try to access the value associated with a key that hasn't been defined in a dictionary, you'll get a key error.
Example:
#python
my_dict = {"name": "John", "age": 25}
print(my_dict["gender"])
In this example, we are trying to access the value for the key "gender", which does not exist in the dictionary.
Fix:
#python
my_dict = {"name": "John", "age": 25}
print(my_dict.get("gender", "Key not found"))
Here, we use the get() method to access the value for the key "gender". The second argument of the get() method specifies the default value to return if the key does not exist.
Attribute Errors In Python:
Attribute errors occur when you try to access an attribute of an object that doesn't exist, or when you try to access an attribute in the wrong way.
There are several different types of attributes in Python:
- Instance attributes: These are attributes that belong to a specific instance of a class.
- Class attributes: These are attributes that belong to a class rather than an instance.
- Static attributes: These are attributes that belong to a class, but can be accessed without creating an instance of the class.
Example:
#python
my_list = [1, 2, 3, 4]
my_list.append(5)
my_list.add(6)
In this example, we are trying to add an item to the list using the add() method, which does not exist for lists.
Fix:
#python
my_list = [1, 2, 3, 4]
my_list.append(5)
Here, we use the append() method to add an item to the list.
Error Handling In Python
When an error and an exception are raised then we handle that with the help of the Handling method.
Handling Exceptions With Try/Except/Finally:
We can handle errors by the Try/Except/Finally method. we write unsafe code in the try, fall back code in except and final code in finally block.
Example:
#python
# put unsafe operation in try block
try:
print("code start")
# unsafe operation perform
print(1 / 0)
# if error occur the it goes in except block
except:
print("an error occurs")
# final code in finally block
finally:
print("All Done!!!")
Output:
code start
an error occurs
All Done!!!
Raising For exceptions For a Predefined Condition:
When we want to code for the limitation of certain conditions then we can raise an exception.
Example:
#python
# try for unsafe code
try:
amount = 1999
if amount < 2999:
# raise the ValueError
raise ValueError("please add money in your account")
else:
print("You are eligible to purchase DSA Self Paced course")
# if false then raise the value error
except ValueError as e:
print(e)
Output:
please add money in your account
Conclusion:
In this article, we covered some of the most common errors in Python and how to fix them. By understanding these errors and how to fix them, you can become a more confident and effective Python programmer.
PLEASE LIKE, COMMENT AND SHARE...
Top comments (4)
Nice article bro
Thanks
Well detailed sir, keep it up ๐๐ซก
Thanks boss