Python Exception Handling Explained
Python Exception Handling Explained
Except block-
An except block contains additional code that will be executed only if some exception is raised in the try block.
But if there is no error then none of the except blocks will be executed.
except Exception Name:
[ code for exception handling]
Else block- If there is no error then none of the except blocks will be executed. In this case, the statements
inside the else block will be executed.
Example:
try:
n=50
d=int (input ("Enter the denominator"))
q=(n/d)
except ZeroDivisionError:
print ("Denominator as ZERO.... not allowed")
else:
print(q)
print ("Division successful")
In the above example, if there is no error in the try block then, except block will not execute, in this case else
block statements that is q value and “Division successful” is displayed.
[Link] try..except..else…finally block with an example.
Ans: try block-
While writing a program, a user might doubt an exception to occur in a particular part of the code. Such
suspicious lines of codes are put inside a try block.
Syntax:
try:
[ program statements where exceptions might occur]
Except block-
An except block contains additional code that will be executed only if some exception is raised in the try block.
But if there is no error then none of the except blocks will be executed.
except ExceptionName:
[ code for exception handling]
Else block- If there is no error then none of the except blocks will be executed. In this case, the statements
inside the else block will be executed.
Finally block: - The statements inside the finally block is always executed whether an exception has occurred
in the try block or not. If used, finally should always be placed at the end after try, except and else block.
Example:
try:
n=50
d=int (input ("Enter the denominator"))
q=(n/d)
except ZeroDivisionError:
print ("Denominator as ZERO.... not allowed")
else:
print(q)
print ("Division successful")
finally:
print (“Program Ends”)
In the above program, the message “Program Ends” will be displayed irrespective of whether an exception
is raised or not.
4. Explain any five built-in exceptions that can be raised in python.
Ans. 1. ImportError: It is raised when the requested module definition is not found.
Example: import Math
ModuleNotFoundError: No module named 'Math'
[Link]: It is raised when the file specified in a program statement cannot be opened.
Example: file = open ("[Link]", "r")
IOError: No such file: '[Link]'
3. ZeroDivisionError: It is raised when the denominator in a division operation is zero.
Example: print (50/0)
ZeroDivisionError: division by zero
4. IndexError: It is raised when the index in a sequence is out of range.
Example: n= [40,50,60]
print (n [4])
IndexError: list assignment index out of range
Ans:
2. Explain pickle module. [5m]
• The pickle module deals with binary files.
• Here, data are not written but dumped and similarly, data are not read but loaded.
• The Pickle Module must be imported to load and dump data.
• The pickle module provides two methods –
dump() and load() to work with binary files for pickling and unpickling, respectively.
• Serialization is the process of transforming data or an object in memory (RAM) to a stream of bytes called
byte streams.
• De-serialization or unpickling is the inverse of pickling process where a byte stream is converted back to
Python object
Ans:
[Link] a note on opening a file.
Ans: 1. To open a file in Python, we use the open() function.
Syntax of open() :
file_object= open(file_name, access_mode)
[Link] file_object establishes a link between the program and the data file stored in the permanent storage.
3. file_name- refers the name of the file that has to be opened.
4. access_mode- Here mode means the operation for which the file has to be opened like for reading,
writing, or for appending. The default mode is read mode.
seek() method:
This method is used to position the file object at a particular position in a file.
The syntax of seek() is:
file_object.seek(offset [, reference_point])
where, offset is the number of bytes by which the file object is to be moved.
reference_point indicates the starting position of the file object.
That is, with reference to which position, the offset has to be counted. It can have any of the following
values:
0 - beginning of the file
1 - current position of the file
2 - end of file
By default, the value of reference point is 0.
TWO MARKS QUESTIONS:
1. Differentiate between the following-
i. write () and writelines() method
Ans: i. write () –
• write() method takes a string as an argument and writes it to the text file.
• write() returns the number of characters written on to the file.
ii. writelines() –
• This method is used to write multiple strings to a file. We need to pass an iterable object like lists,
tuple, etc. containing strings to the writelines() method.
• The writelines() method does not return the number of characters written in the file.
[Link] the different forms of read statement.
Ans: i. read() – This method is used to read a specified number of bytes of data from a data file.
The syntax of read() method is:
file_object.read(n)
example:
>>>myobject=open("[Link]",'r’)
>>> [Link](10)
[Link]( ) - This method reads one complete line from a file where each line terminates with a newline
(\n) character.
>>>myobject=open("[Link]",'r’)
>>> print ([Link]())
iii. readlines()- This method reads all the lines and returns the lines along with newline as a list of strings.
>>> myobject=open("[Link]", 'r’)
>>> print([Link]()) ['Hello everyone\n', 'Writing multiline strings\n', 'This is the third line’]
>>> [Link]()
2. Write a note on Binary file.
Ans: 1. Binary files are stored in terms of bytes (0s and 1s)
[Link] files are not human readable.
3. Binary files are having extension .dat
De-serialization or unpickling is the inverse of pickling process where a byte stream is converted back to
Python object.
STACK
MCQs
[1] A ____________ is a way to store, organize, or manage data in efficient and productive manner.
Data Structure
[2] A stack is one of the following types of data structure?
a) Linear b) Dynamic c) Circular d) All of these
[3] Stack data structure is following ____________ principle.
LIFO
[4] In stack data can be inserted or deleted from ____________ only.
Top
[5] The insert operation in the stack is known as pop. (True/False)
[6] You can replace any element position in the stack. (True/False)
7] The peek operation refers to accessing/inspecting the top element in the stack. (True/False)
[8] A condition raise due to the stack is full is known as ___________.
a) Underflow b) Overflow c) List is full d) Completely Filled
[9] While popping the element from the stack, a condition will be raised, this condition is known as
____________.
a) Underflow b) Overflow c) List is Empty d) Blank List
[10] Stack overflow condition is raised in ____________ operation whereas Stack underflow condition is raised in
_____________ operations.
Push, Pop
Two Marks Questions:
1] What do you mean by data structure. Give example.
Ans: A data structure defines a mechanism to store, organize and access data along with operations that can be
efficiently performed on the data.
1. String – Contains sequence of characters
2. List – Contains sequence of different data types
5. Mention the methods that are used for implementation of the stack.
Ans: 1. Append ()
2. pop ()
[Link] are the underflow and overflow conditions?
Ans. Underflow is the condition which occurs when stack is empty while trying to delete elements.
Overflow is the condition which occurs while inserting an element when memory is exhausted.
[Link] is the significance of top in stack?
Ans: The top function returns the topmost element of the stack.
8. What is the Top status when stack is underflow & overflow?
Ans: Top=-1 indicates stack is underflow.
Top=n-1 indicates stack is overflow.
Postfix
Symbol Action Stack
Expression
*
* Push
↑
A
(*
( Push
↑
( Push ((*
↑
+((* AC
+ Push
↑
D ACD
(*
Pop till one opening bracket is popped and
)
add popped operator to expression
↑
ACD+
/(*
/ Push
↑
E ACD+E
*
Pop till one opening bracket is popped and
) ACD+E/
add popped operator to expression
↑
End of
Pop all and add to expression #Empty ACD+E/*
expression
iii. A+B-C*D
Answer
Given,
A+B-C*D
Scanning from left to right:
Postfix
Symbol Action Stack
Expression
+ A
+ Push in stack
↑
B AB
- - AB+
Equal precedence to +. Pop from stack, add in
↑
expression then push this operator(-)
*- AB+C
* Higher precedence than (-), hence Push
↑
D AB+CD
End of
Pop all and add to expression #Empty AB+CD*-
expression
Intermediate
Symbol Action Stack
output
3
3 Push
↑
53
5 Push
↑
#Empty
18
1 Push
↑
#Empty
Hence, AB + C * = 35 + 1 * = 8
[Link]*C/D* WHERE A=3, B=5, C=1, D=4
Answer
AB * C / D * = 35 * / 4 *
Scanning from left to right :
Intermediate
Symbol Action Stack
output
3 Push 3
53
5 Push
↑
#Empty
1 Push 1 15
↑
#Empty
4 15
4 Push
↑
#Empty
15 * 4 = 60
* Pop twice, Evaluate and Push back 60
Hence, AB * C / D * = 35 * / 4 * = 60
[Link]:
def DELETIONFRONT(mydeQue):
if (len(mydeQue)==0):
print(“deque is empty”)
else:
return [Link](0)
CHAPTER-5 SORTING
FIVE MARKS QUESTIONS:
[Link] the bubble sort with an example.
Ans: Bubble sort is a sorting technique, that sorts a given list of elements by repeatedly comparing
the adjacent elements and swapping them if they are unordered.
➢ In order to arrange elements in ascending order, the largest element is identified after each
pass and placed at the correct position in the list. This can be considered as the largest
element being ‘bubbled up’. Hence the name Bubble sort.
➢ Example: list = [8, 7, 13, 1, -9, 4]
[Link] the selection sort with an example.
• Ans: In Selection Sort, the list is considered to be divided into two lists –
[Link] left list containing the sorted elements.
[Link] right list containing the unsorted elements.
• The smallest element is selected from the unsorted array and swapped with the leftmost
element, and that element becomes a part of the sorted array. The process continues for the
next element in the unsorted array till the list is sorted.
➢ Example: list = [8, 7, 13, 1, -9, 4]
[Link] the insertion sort with an example.
Ans: Insertion sort divides the list into sorted and unsorted list. Each element in the unsorted list is
considered one by one and is inserted into the sorted list at its appropriate position.
In each pass, the sorted list is traversed from the backward direction to find the position where the
unsorted element could be inserted. Hence the sorting method is called insertion sort.
Example:
THREE MARKS QUESTIONS:
[Link] is sorting? Mention different types of sorting.
Ans: Sorting is the process of ordering or arranging a given collection of elements in some particular
order.
Different types of sorting are-
[Link] sort
[Link] sort
[Link] sort.
[Link] an Algorithm of Bubble sort.
Ans: BUBBLESORT (numList, n)
Step 1: SET i = 0
Step 2: WHILE i< n REPEAT STEPS 3 to 8
Step 3: SET j = 0
Step 4: WHILE j< n-i-1, REPEAT STEPS 5 to 7
Step 5: IF numList[j] > numList[j+1] THEN
Step 6: swap(numList[j] , numList[j+1])
Step 7: SET j=j+1
Step 8: SET i=i+1
[Link] an Algorithm of Selection sort.
Ans: SELECTIONSORT( numList, n)
Step 1: SET i=0
Step 2: WHILE i< n REPEAT STEPS 3 to 11
Step 3: SET min = i, flag = 0
Step 4: SET j= i+1
Step 5: WHILE j< n REPEAT steps 6 to 10
Step 6 : If numlist[j] < numlist[min] Then
Step 7: min = j
Step 8: flag = 1
Step 9: IF flag = 1 THEN
Step 10: swap(numList[i],numList[min])
Step 11: SET i=i+1
[Link] an Algorithm of Insertion sort.
Ans: INSERTIONSORT( numList, n)
Step 1: SET i=1
Step 2: WHILE i< n REPEAT STEPS 3 to 9
Step 3: temp = numList[i]
Step 4: SET j = i-1
Step 5: WHILE j> = 0 and numList[j]>temp,REPEAT STEPS 6 to 7
Step 6: numList[j+1] = numList[j]
Step 7: SET j=j-1
Step 8: numList[j+1] = temp
Step 9: set i=i+1
[Link]:
a. Constant time algorithms.
Ans: Any algorithm that does not have any loop will have time complexity as 1. Such
algorithms are known as Constant time algorithms.
b. Linear time algorithms.
Ans: Any algorithm that has a loop will have the time complexity as n. Such algorithms are
known as Linear time algorithms.
c. Quadratic time algorithms.
Ans: A loop within a loop (nested loop) will have the time complexity as n2. Such algorithms
are known as Quadratic time algorithms.,
CH – 6 SEARCHING
TWO MARKS QUESTIONS:
[Link] is searching?
• Ans: Searching means locating a particular element in a collection of elements.
[Link] a note on Linear search.
• Ans: It is a searching technique where every element of a given list is compared with the item to be
searched. This process continues until an element matching the key is found and we declare that the search
is successful else search is unsuccessful.
• It is also called sequential search or serial search.
[Link] a note on Binary search.
Ans: Binary search takes a sorted/ordered list and divides it in the middle. It then compares the middle element
with the key to be searched. If the middle element matches the key, the search is declared successful and the
program ends. If the middle element is greater than the key, the search repeats only in the first half of the list. If
the middle element is lesser than the key, the search repeats only in the second half of the list.
[Link] a note on Search by Hashing.
Ans: • Hash based searching requires only one key comparison to discover the presence or absence of a key,
provided every element is present at its designated position decided by a hash function.
5. What is collision and collision resolution?
• Ans: When two elements map to the same slot in the hash table, it is called collision.
• The process of identifying a slot for the second and further items in the hash table in the event of collision,
is called collision resolution.
[Link] the applications of binary search.
Ans:1. – Searching a dictionary or a telephone directory, finding the element with minimum value or maximum
value in a sorted list, etc.
2. Indexing in databases, implementing routing tables in routers, data compression code, etc.
7. What is perfect hash function?
Ans. A perfect hash function maps every input key to a unique index in the hash table. If the hash function is
perfect, collisions will never occur.
THREE MARKS QUESTIONS:
1. Mention the types of searching methods.
Ans: 1. Linear Search
2. Binary Search
3. Search by Hashing
2. Write an algorithm of Linear search.
Ans: LinearSearch(numList, key, n)
Step 1: SET index = 0
Step 2: WHILE index < n, REPEAT Step 3
Step 3: IF numlist[index]= key THEN
PRINT “Element found at position”, index+1
STOP
ELSE
index = index+1
Step 4: PRINT “Search unsuccessful”
Observe that after four comparisons, the algorithm found the key 17 and will display ‘Element found at
position 4’.
2. Explain binary search with example.
• Ans. In binary search, the key to be searched is compared with the element in the middle of a sorted list.
This could result in either of the three possibilities:
i) the element at the middle position itself matches the key or
ii) the element at the middle position is greater than the key or
iii) the element at the middle position is smaller than the key
• If the element at the middle position matches the key, we declare the search successful and the searching
process ends.
• If the middle element is greater than the key it means that if the key is present in the list, it must surely be
in the first half.
• If the middle element is less than the key, it means if the key is present in the list, it must be in the second
half.
Example : let us search for key 2 in the list. numList = [2,3,5,7,10,11,12,17,19,23,29,3 1,37,41,43]
•
• After computing the hash values, each element is inserted at its designated position in the hash table:
•
4. Use the hash function: h(element)= element%10 to store the collection of numbers: [44, 121, 55, 33, 110,
77, 22, 66] in a hash table. Display the hash table created. Search if the values 11, 44, 88 and 121 are
present in the hash table, and display the search results.
5. Following is a list of unsorted/unordered numbers: [50, 31, 21, 28, 72, 41, 73, 93, 68, 43] • Use linear
search to determine the position of 72 in the list.
• Sort the above list and use binary search to determine the position of 93 in the sorted list.
{For the above two questions (4Q & 5Q) refer workbook}
1. Consider the temperature (in Celsius) of 7 days of a week as 34, 34, 27, 28, 27, 34, 34. Identify the
appropriate statistical technique to be used to calculate the following:
i. Find the average temperature.
ii. Find the temperature Range of that week.
iii. Find the standard deviation temperature.
2. Consider the marks scored by students in a subject given [90,80,70,95,95,85,80] calculate the statistical
technique for the following:
• Find the range of marks scored.
• Find the standard deviation of marks.
2. The following are the runs scored by two batsman A and B of team Alpha on the first five innings of three
consecutive test matches
Batsman A:77,89,45,63,70 runs per innings
Batsman B: 100,45,122,88,99 runs per innings
a. Find standard deviation of scores of both Batsman A and B
b. Based on standard deviation who is more consistent in scoring.