DEBUGGING PROGRAMS
Computer Science
Class -XI
Code No. 083
2023-24
CLASS-XI
SUBJECT: COMPUTER SCIENCE (083) – PYTHON
INDEX
NO. CHAPTER NAME
1 INTRODUCTION TO PYTHON
2 PYTHON FUNDAMENTALS
3 DATA HANDLING
4 FLOW OF CONTROL
5 FUNCTIONS IN PYTHON
6 STRING IN PYTHON
7 LIST IN PYTHON
8 TUPLE IN PYTHON
9 DICTIONARY IN PYTHON
10 SORTING
11 DEBUGGING PROGRAMS
|
CHAPTER-11
DEBUGGING PROGRAMS
11.1 INTRODUCTION:
Errors in a program are known as ‘bugs’.
To remove the errors from a program, known as debugging.
11.2 TYPES OF ERRORS:
1. Compile Time Error
a. Syntax Error
b. Semantics Error
2. Run Time Error
3. Logical Error
1. Compile Time Error: Compile time errors are
those errors that occur at the time of
compilation of the program.
There are two types of compile time errors:
a. Syntax Error: These errors occur due to
violation of grammatical rules of a
programming language.
for example:
TYPES OF ERRORS
COMPILE TIME ERROR
Syntax Errors Semantics Errors
RUN TIME ERROR LOGICAL ERROR
ApnaJila ApnaJila 100
a=10
b=20
if a>b #Syntax error, : is missing
Print(“a is greater than b”) # Syntax error,
P is capital in Print statement
b. Semantics Error: Semantic errors occur
when the statements written in the program are
not meaningful.
Example:
a+b = c # expression cannot come on the
left side of the assignment operator.
2. Run Time Error: Errors that occur during
the execution or running the program are
known as run time errors. When a program
“crashed” or “abnormally terminated” during
the execution, then this type errors are run
time errors.
Example: When a loop executes infinite time.
a=1
while a<5: # value of a is always less than 5,
infinite loop
print(a)
a=a-1
3. Logical Error: These types of errors occur
due to wrong logic. When a program
successfully executes but giving wrong output, then it is known as logical error.
Example:
a=10
b=20
c=30
average=a+b+c/3 #wrong logic to find the average
print(average)
OUTPUT:
40.0
11.3 Exception handling in python:
Exception: The unusual and unexpected condition
other than syntax or logical errors,
encountered by a program at the time of execution,
is called exception.
The purpose of exception handling mechanism is to
provide means to detect and report
an exceptional circumstance, so that appropriate
action can be taken.
Exception handling in python can be done using
try and except blocks.
Syntax:
try:
# Code that may generate an exception
except:
# Code for handling the exception
Example:
num1=int(input("Enter first number :"))
num2=int(input("Enter second number: "))
try:
r=num1/num2
print("Result is :", r)
except:
print("Divided by zero")
OUTPUT:
Enter first number :30
Enter second number: 0
Divided by zero
11.4 Steps to debug a program:
a. Carefully follow the syntax of a language
ApnaJila ApnaJila 102
b. Spot the origin of error
c. Read the type of error and understand it well
d. Use intermediate print statements to know the
value and type of a variable
e. Trace the code carefully
ApnaJila ApnaJila 103
Explanation of Keywords:
a. True and False
True and False are the results of comparison
operations or logical (Boolean) operations in
Python. For example:
>>> 3 = = 3
True
>>> 5 < = 4
False
>>> 7 > 2
True
>>> True or False
True
>>> True and False
False
Note:- True and False in python is same as 1 and 0.
Example:
>>> True = = 1
True
>>> False = = 0
True
>>> True + True
2
b. None
None is a special constant in Python that represents
the absence of a value or a null value.
None does mean False, 0 or any empty list.
Example:
>>> None = = 0
ApnaJila ApnaJila 105
Although this function has a return statement,
it is not reached in every case. The function will
return True only when the input is even.
c. as
as is used to create an alias while importing a module.
Example:
>>> import math as mymath
>>> mymath.sqrt(4)
2.0
d. assert
assert is used for debugging purposes.
assert helps us to find bugs more conveniently.
If the condition is true, nothing happens. But if
the condition is false, AssertionError is
raised.
Syntax:
assert condition, message
example:
>>> x = 7
>>> assert x > 9, “The value is smaller”
Traceback ( most recent call last ):
File “”, line 201, in runcode
File “”, line 1, in
AssertionError: The value is smaller
e. def
def is used to define a user-defined function.
ApnaJila ApnaJila 106
Syntax:
def function-name(parameters) :
f. del
del is used to delete the reference to an object.
Everything is object in Python. We
can delete a variable reference using del
Syntax: del variable-name
>>> a = b = 9
>>>del a
>>> a
Traceback (most recent call last):
File “”, line 201, in tuncode
File “”, line 1, in
NameError : name ‘a’ is not defined
>>>b
9
.
del is also used to delete items from a list or a dictionary:
>>> x = [ ‘p’, ‘q’, ‘r’ ]
>>> del x[1]
>>> x
ApnaJila ApnaJila 107
[‘q’, ‘r’]
g. except, raise, try
except, raise, try are used with exceptions in Python.
Exceptions are basically errors that suggests something
went wrong while executing our
program
try...except blocks are used to catch exceptions in Python.
We can raise an exception explicitly with the raise keyword.
Syntax:
try:
Try-block
except exception1:
Exception1-block
except exception2:
Exception2-block
else:
Else-block
finally:
Finally-block
example:
def reciprocal(num):
try:
r = 1/num
except:
print('Exception caught')
return
return r
print(reciprocal(10))
print(reciprocal(0))
Output
0.1
ApnaJila ApnaJila 108
Exception caught
None
h. finally
finally is used with try…except block to close up
resources or file streams.
i. from, import
import keyword is used to import modules into the
current namespace. from…import is
used to import specific attributes or functions
into the current namespace.
For example:
import math
will import the math module.
Now we can use the sqrt( ) function inside it as
math.sqrt( ). But if we wanted to import just
the sqrt( ) function, this can done using from as
Example :
from math import sqrt
now we can use the function simply as sqrt( ),
no need to write math.sqrt( ).
j. global
global is used to declare that a variable inside
the function is global (outside the function).
If we need to read the value of a global variable,
it is not necessary to define it as global. This
is understood.
If we need to modify the value of a global
variable inside a function, then we must
declare it
with global. Otherwise a local variable with
that name is created.
Example:
globvar = 10
def read1( ):
print(globvar)
def write1( ):
global globvar
globvar = 5
def write2( ):
globvar = 15
read1( )
ApnaJila ApnaJila 109
write1( )
read1( )
write2( )
read1( )
Output
10
5
5
k. in
in is used to test if a sequence (list, tuple, string etc.
) contains a value. It returns True if the
value is present, else it returns False. For example:
>>> a = [1, 2, 3, 4, 5]
>>> 5 in a
True
>>> 10 in a
False
The secondary use of in is to traverse through
a sequence in for loop.
for i in 'hello':
print(i)
Output
h
e
l
l
o
l. is
is keyword is used in Python for testing object identity.
While the = = operator is used to test
if two variables are equal or not, is is used to test if the
two variables refer to the same object.
It returns True if the objects are identical and False if not.
>>> True is True
True
ApnaJila ApnaJila 110
>>> False is False
True
>>> None is None
True
We know that there is only one instance of True,
False and None in Python, so they are
identical.
>>> [ ] == [ ]
True
>>> [ ] is [ ]
False
>>> { } == { }
True
>>> { } is { }
False
An empty list or dictionary is equal to another
empty one. But they are not identical objects as
they are located separately in memory. This is
because list and dictionary are mutable (value
can be changed).
>>> '' == ''
True
>>> '' is ''
True
>>> ( ) == ( )
True
>>> ( ) is ( )
True
Unlike list and dictionary, string and tuple are
immutable (value cannot be altered once
defined). Hence, two equal string or tuple are
identical as well. They refer to the same memory
location.
m. lambda
lambda is used to create an anonymous function
(function with no name). It is an
inline function that does not contain a return
statement. It consists of an
expression that is evaluated and returned.
example:
a = lambda x: x*2
for i in range(1,6):
print(a(i))
ApnaJila ApnaJila 111
Output
2
4
6
8
10
Note: range (1,6) includes the value from 1 to 5.
n. nonlocal
The use of nonlocal keyword is very much
similar to the global keyword. nonlocal is
used to
declare a variable inside a nested function
(function inside a function) is not local to it.
If we need to modify the value of a
non-local variable inside a nested function,
then we must
declare it with nonlocal. Otherwise a local
variable with that name is created inside the nested
function.
Example:
def outer_function( ):
a = 5
def inner_function( ):
nonlocal a
a = 10
print("Inner function: ",a)
inner_function ( )
print("Outer function: ",a)
outer_function( )
Output
Inner function: 10
Outer function: 10
Here, the inner_function( ) is nested within
the outer_function( ).
The variable a is in the outer_function( ).
So, if we want to modify it in the inner_function( ),
we must declare it as nonlocal. Notice that a
is not a global variable.
Hence, we see from the output that the variable
was successfully modified inside the
nested inner_function( ).
The result of not using the nonlocal keyword
is as follows:
def outer_function ():
a = 5
ApnaJila ApnaJila 112
def inner_function( ):
a = 10
print("Inner function: ",a)
inner_function( )
print("Outer function: ",a)
outer_function( )
Output
Inner function: 10
Outer function: 5
Here, we do not declare that the variable a
inside the nested function is nonlocal. Hence,
a new
local variable with the same name is created,
but the non-local a is not modified as seen in our
output.
o. pass
pass is a null statement in Python. Nothing
happens when it is executed. It is used
as a placeholder.
Suppose we have a function that is not implemented
yet, but we want to implement it in the
future. Simply writing,
def function(args):
in the middle of a program will give us IndentationError.
Instead of this, we construct a blank
body with the pass statement.
def function(args):
pass
p. while
while is used for looping.
i = 5
while(i):
print(i)
i = i – 1
Output
5
4
3
2
1
q. with
with statement is used to wrap the execution of
a block of code within methods
defined by the context manager.
Context manager is a class that implements enter
and exit methods. Use of with statement
ensures that the exit method is called at the
end of the nested block.
Example
with open('Book.txt', 'w') as my_book:
my_file.write(' Computer Science ')
This example writes the text Computer Science
to the file Book.txt. File objects
have enter and exit method defined within them,
so they act as their own context manager.
First the enter method is called, then the code
within with statement is executed and finally
the exit method is called. exit method is called
even if there is an error. It basically closes the
file stream.
r. yield
yield is used inside a function like a return
statement. But yield returns a generator.
Generator is an iterator that generates one item
at a time. A large list of value will take up a
lot of memory. Generators are useful in this
situation as it generates only one value at a time
instead of storing all the values in memory.
Example:
>>> g = (2**x for x in range(100))
will create a generator g which generates the
values 20 to 299. We can generate the numbers
using the next( ) function as shown below:
>>> next(g)
1
>>> next(g)
2
>>> next(g)
4
>>> next(g)
8
ApnaJila
>>> next(g)
16
And so on…
This type of generator is returned by the yield
statement from a function.
Example:
def generator( ):
for i in range(6):
yield i*i
g = generator( )
for i in g:
print(i)
Output
0
1
4
9
16
25
|
|