Python Programming Debugging
Python Programming Debugging
Syntax Errors
Logical Errors
Syntax Errors
A syntax error is one of the most basic types of error in programming. Whenever
we do not write the proper syntax of the python programming language (or any
other language) then the python interpreter or parser throws an error known as
a syntax error. The syntax error simply means that the python parser is unable to
understand a line of code.
number = 100
if number > 50
print("Number is greater than 50!")
File "test.py", line 3
if number > 50
^
SyntaxError: invalid syntax
number = 100
divided_by_zero = number / 0
print(divided_by_zero)
Traceback (most recent call last):
File "d:\test.py", line 2, in <module>
divided_by_zero = number / 0
ZeroDivisionError: division by zero
Zero Division Error is raised by the Python interpreter when we try to divide any number
by zero.
Exception Handling
Errors that occur at runtime (after passing the syntax test) are called exceptions or
logical errors.
An exception is an unexpected event that occurs during program execution.
For example,
divide_by_zero = 7 / 0
The above code causes an exception as it is not possible to divide a number by 0.
print(add(2,7))
print(add(5,10))
print(add(7,'a'))
print(add(12,2))
print('Execution done')
def add(x,y):
try:
return (x+y)
except TypeError:
return ("Invalid")
print(add(2,7))
print(add(5,10))
print(add(7,'a'))
print(add(12,2))
print('Execution done')
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of the try- and
except blocks.
Try and Multiple Except
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Else Clause
The code enters the else block only if the try clause does not raise an exception.
divide(3, 2)
divide(3, 0)
Output
Yeah ! Your answer is : 1
Sorry ! You are dividing by zero
Exception handling with try, except, else, and finally
Try: This block will test the excepted error to occur
Except: Here you can handle the error
Else: If there is no exception then this block will be executed
Finally: Finally block always gets executed either exception is generated or not
def divide(x, y):
try:
result = x // y
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
else:
print("Yeah ! Your answer is :", result)
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
divide(3, 2)
divide(3, 0)
Whenever the code gets an exception, the traceback will give the information
about what went wrong in the code. The Python traceback contains great
information that can help you find what is going wrong in the code. The
traceback includes the error message, the line number of the line that caused
the error, and the sequence of the function calls that led to the error. This
sequence of calls is called the call stack.
The traceback is displayed by Python whenever a raised exception goes
unhandled.
Example:
mylist = [1, 2, 3]
print(mylist[10])
In this example, we are trying to access the 10th element of the list. With only
3 elements present in the list it will give Runtime error. When this program is
executed you will get the following traceback.
This traceback error has all the information about why this runtime error
occurred. Last line of the traceback tells you about what type of error occurred
along with relevant information. Previous lines of traceback points to the code
in which error occurred.
In python it is best to read traceback from bottom to top.
GREEN BOX shows the what type of error occurred .
BLUE BOX shows the relevant information about error
ORANGE BOX shows traceback statement for recent calls, below The firstRuntime Error:
Traceback (most recent call last):
File “”, line 1, in
ModuleNotFoundError: No module named ‘asdf’ line of each call contains information
like the file name, line number, and module name
RED underlined part shows exact line where exception occurred.
Example:
number = 1
print(numb)
Assertions
Assertion is a programming concept used while writing a code where the user
declares a condition to be true using assert statement prior to running the
module. If the condition is True, the control simply moves to the next line of
code. In case if it is False the program stops running and returns AssertionError
Exception.
Example:
try:
x=1
y=0
assert y != 0, "Invalid Operation"
print(x / y)
Breakpoints
A breakpoint can be set on a specific line of code and forces the debugger to pause
whenever the program execution reaches that line.