[go: up one dir, main page]

0% found this document useful (0 votes)
40 views14 pages

Python Exception Handling Guide

passing package
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views14 pages

Python Exception Handling Guide

passing package
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

IMPORTANT QUESTIONS

CHAPTER 1 : EXCEPTION HANDLING IN PYTHON

[Link] a note on syntax error.

 A syntax error in programming occurs when the code violates the rules of
the programming language.
 Syntax errors are detected when we have not followed the rules of the
particular programming language while writing a program. These errors
are also known as parsing errors.

2. Define (a) Exception (b) Exception handling.

a) Exception – An exception in python object that represents an error, that


occurs during the execution of program.
b) Exception Handling - Exception handling in Python refers to managing
runtime errors that may occur during the execution of a program.

3. Explain commonly used Built-in exceptions in python.

 Syntax Error: It is raised when there is an error in the syntax of the


Python code.
 Value Error: It is raised when there is a wrong value in a specified data.
type.
 Zero Division Error: It is raised when the denominator in a division
operation is zero.
 IO Error: It is raised when the file specified in a program statement
cannot be opened.
 Index Error: It is raised when an index of a sequence does not exist.

4. Explain raising exceptions.

Each time when an error is detected in a program, the Python interpreter


raises (throws) an exception. Programmers can also raise exceptions using the
raise and assert statements.

a) The raise statement:


The raise statement can be used to throw an exception.
Syntax: raise exception_name[(optional argument)]
The argument is generally a string that is displayed when the exception is
raised.
Example:
x = -1
if x < 0:
raise Exception("Sorry, number should not be below
zero")
b) The assert statement:
An assert statement in Python is used to test an expression in the
program code. If the result after testing comes false, then the exception is
raised.
This statement is generally used in the beginning of the function.

Syntax:
assert Expression[,arguments]
Example:
a=4
b=0
print("The value of a / b is : ")
assert b != 0, "Zero Division Error"
print(a / b)

5. Write a note on raise statement.

The raise statement:

The raise statement can be used to throw an exception.


Syntax: raise exception_name[(optional argument)]
The argument is generally a string that is displayed when the exception is
raised.
Example:
x = -1
if x < 0:
raise Exception("Sorry, number should not be below zero")

[Link] a note on assert statement.

The assert statement:

An assert statement in Python is used to test an expression in the


program code. If the result after testing comes false, then the exception is
raised.
This statement is generally used in the beginning of the function.

Syntax:
assert Expression[,arguments]
Example:
a=4
b=0
print("The value of a / b is : ")
assert b != 0, "Zero Division Error"
print(a / b)

[Link] is exception handling ? explain how the exception are handled


(or) explain the need for exception handling.

Each and every exception has to be handled by writing additional code in a


program to give proper messages or instructions to the user on encountering an
exception. This process is known as exception handling.
Need for Exception Handling

a) Python categories exceptions into distinct types so that specific exception


handlers can be created for each type.

b) Exception handler keeps the main part of your program separate from the
error detection and correction code. This does not affect the main logic of the
program.

c) The compiler or interpreter keeps track of the exact position where the error
has occurred.

d) Exception handling can be done for both user-defined and built-in exceptions.

8. Explain the process of handling exceptions.

 When an error occurs, Python interpreter creates an object called the


exception object.
 The object is handed over to the runtime system so that it can find an
appropriate code to handle this particular exception.
 This process of creating an exception object and handing it over to the
runtime system is called throwing an exception.
 The runtime system searches the entire program for a block of code,
called the exception handler that can handle the raised exception.
 This hierarchical search in reverse order continues till the exception
handler is [Link] entire list of methods is known as call stack.
 This process of executing a suitable handler is known as catching the
exception.
 If the runtime system is not able to find an appropriate exception after
searching all the methods in the call stack, then the program execution
stops.

9. Explain try and except block.

The try...except Block

 The try block encloses the code that might raise an exception.
 The except block specifies how to handle a particular exception.

Syntax:

try:
[ program statements where exceptions might occur]
except [exception-name]:
[ code for exception handling]

Example for try and except

10. Explain multiple except clause.

You can use multiple except clauses to catch and handle different types of
exceptions in a single try block. This allows you to specify different handling
mechanisms for various types of errors that might occur in your code.

11. Explain try...except…else clause

The try block contains the code that might raise an exception. The except
block(s) handles the exceptions that are raised. The else block is optional and is
executed only if no exceptions are raised within the try block.
[Link] finally clause.

Finally Clause The finally block is always executed, regardless of whether an


exception occurred or not.

CHAPTER 2: FILE HANDLING IN PYTHON

[Link] is file? Mention the types of file.

A File is a named location on a secondary storage media where data are


permanently stored for later access.

Types of Files— text file and binary file.

2. Write the difference between text file and binary file.

TEXT FILE BINARY FILE


Contains sequence of Contains raw binary data (image,
characters(letters, numbers audio, video etc)
and symbols)
It is human readable It is not human readable
Each line ends with special No line endings as in text file.
character(EOL)
Can be easily modified Requires specific software to
modify.
Error detection is easy Error deletion is difficult
Eg : .txt, .py , .csv Eg: .jpg, .mp3, .png etc
3. Write syntax and example to open a text file.

To work with a file, you first need to open it using open() function.

Syntax: file_object = open("file_name", "access_mode")

file_name is the name of the file.

Access mode is an optional argument that represents the mode in


which the file has to be accessed by the program.

Example: file = open("[Link]", "r") .

4. What is the need of using with clause while opening a file? Write
syntax and example.

In Python, we can also open a file using with clause.

The advantage of using with clause is that any file that is opened using this
clause is closed automatically.

Syntax: with open (file_name, access_mode) as file_object:

Example: with open(“[Link]”,”r+”) as myObject:

content = [Link]()

Here, we don’t have to close the file explicitly using close() statement. Python
will automatically close the file.

5. Write a note on closing a file.

 Python provides a close() function.


 While closing a file, the system frees the memory allocated to it.
Syntax: file_object.close()
 Python makes sure that any unwritten or unsaved data is flushed off
(written) to the file before it is closed.

6. Explain write() and writelines() with example.

 write()- write() method is used to write a single string. It returns the


number of characters being written on to file.
Example: file=open(“[Link]”,”w”)
[Link](“hello world\n”)
12
[Link]()
 writeline()- 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.
Example : file = open(“[Link]”,”w”)
lines=[“hello everyone\n”,”writing multiple strings”]
[Link](lines)
[Link]()

7. Explain read(),readline() and readlines() with example.

 read()- The read() method is used to read a specified number of bytes of


data from a datafile.
Example: file=open(“[Link]”,”r”)
[Link](10)
“hello ever”
[Link]()
 readline([n]) – This method reads one complete line from a file where
each line terminates with a newline character(‘\n’).

example : file=open(“[Link]”,”r”)
[Link](10)
“hello ever”
[Link]()
 readlines() – This method reads all the lines and returns the lines along
with newline(‘\n’) as a list of strings.
Example: file=open(“[Link]”,”r”)
print([Link]())
[“hello everyone\n”,”writing multiple strings”]
[Link]()

8. Explain tell() and seek() method.

 The tell() method: This function returns an integer that specifies the
current position of the file object in the file.
Syntax: file_object.tell()
 The seek() method: This method is used to position the file object at a
particular position in a file.
Syntax: file_object.seek(offset [, reference_point])
here, 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.
0 - beginning of the file
1 - current position of the file
2 - end of file By default,
The value of reference_point is 0, i.e. the offset is counted from the
beginning of the file.

[Link] a python program writing and reading to a text file.

file=open(“[Link]”,”w”)
name=input(“enter your name :”)
[Link](name)
[Link]()
print(“reading the contents of file”)
file=open(“[Link]”,”r”)
for str in file:
print(str)
[Link]()

10. Explain file access modes with example.


 <r>- opens the file in read only mode.
Eg : file=open(“[Link]”,”r”)
 <rb> - opens the file in read and binary mode.
Eg : file=open(“[Link]”,”rb”)
 <w> - opens the file in write mode.
Eg : file=open(“[Link]”,”w”)
 <a> - opens the file in append mode.
Eg : file=open(“[Link]”,”a”)
 <r+>or<=r> - opens the file in both read and write mode.
Eg : file=open(“[Link]”,”r+”)

11. Write the file mode that will be used for opening the following files .
Also write the python statements to open the following files.
a. A text file “[Link]” in both read and write mode.
b. A binary file “[Link]” in write mode.
c. A text file “[Link]” in append and read mode.
d. A binary file “[Link]”in read only mode.
e. A binary file “[Link]” in read, write and binary mode.

a. file = open(“[Link]”,”r+”)
b. file=open(“[Link]”,”wb”)
c. file=open(“[Link]”,”a+”)
d. file=open(“[Link]”,”rb”)
e. file=open(“[Link]”,”rb+”)

12. Explain pickle module.


 The pickle module in python deals with serialization and deserialization
objects.
 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. These byte streams in a
binary file can then be stored in a disk or in a database or sent through a
network. Serialization process is also called pickling.
 De-serialization or unpickling is the inverse of pickling process where
a byte stream is converted back to Python object.
13. Explain the dump() method.
The dump() method:This method is used to convert (pickling) Python objects
for writing data in a binary file.
The file in which data are to be dumped, needs to be opened in binary write
mode (wb).
Syntax: dump(data_object, file_object)
Example : import pickle
list=[1,”geethika”,”F”,26]
file=open(“[Link]”,”wb”)
[Link](list,file)
[Link]()
14. Explain the load() method.
The load() method: This method is used to load (unpickling) data from a
binary file .
The file to be loaded is opened in binary read (rb) mode.
Syntax: Store_object = load(file_object)
Example : import pickle
print(“the data in file are”)
file=open(“[Link]”,”rb”)
object=[Link](file)
[Link]()
print(object)

CHAPTER 3 : STACKS
1. What is Stack? Which principle does stack follows.
A stack is an ordered collection of elements where the addition of new
elements and the removal of existing elements always take place at the
same end called TOP.
Stack follows LIFO (Last-In First-Out) principle.
2. Write the applications of stack in programming.
 To reverse a string.
 redo/undo mechanism in text/image editor.
 Backtracking.
 To solve Tower of Hanoi.
 Expression Evaluation.
3. Explain the operations performed on stack.
 PUSH –
 adds a new element at the TOP of the stack. It is an
insertion operation.
 We can add elements to a stack until it is full.
 Trying to add an element to a full stack results in an
exception called ‘overflow’.
 POP-
 operation is used to remove the top most element of the
stack. It is a delete operation.
 We can delete elements from a stack until it is empty.
 Trying to delete an element from an empty stack results in
an exception called ‘underflow’.
4. Explain the types of arithmetic expression.
 Infix expression – operators are placed in between the operands.
Eg : a+b.
 Prefix expression – operators are placed before operands. Eg : +ab.
 Postfix expression – operators are placed after operands. Eg : ab+.
5. What is polish notation?
Prefix notation are also called as polish notation, where the operators are
placed before operands.
6. What is reverse polish notation?
Postfix notation are also called as reverse polish notation, where the
operators are placed after operands.
7. Convert the infix expression to postfix expression using stack:
Problem-1
Convert a given infix expression A+B*C into equivalent postfix expression
using a stack.

Problem-2
Convert a given infix expression A*(B+C-D) into equivalent postfix
expression using a stack.
Problem-3

Convert a given infix expression (X + Y) / (Z*8) into equivalent postfix


expression using a stack.

8. Evaluate the following postfix expression:


Example-1
Evaluation of postfix expression 2 3 4 * +

Example-2

Evaluation of postfix expression 3 4 * 2 5 * +


CHAPTER 4 : QUEUE

1. What is queue? Which operation does the queue follow.


Queue is an ordered collection of elements, where the insertion of
elements takes place at rear end and removal of elements takes place at
front end.
Queue follows FIFO (First In First Out) principle.

2. Write a note on FIFO.

First In First Out (FIFO)

 Queue follows the principle of First In First Out (FIFO), since


the element entering first in the queue will be the first one
to come out of it.
 It is also known as a First Come First Served (FCFS)
approach.
 Queue is an arrangement in which new items always get
added at one end, usually called the REAR. REAR is also
known as TAIL.
 In Queue, items always get removed from the other end,
usually called the FRONT of the queue. FRONT is also known
as HEAD.

3. Write the applications of queue.

 Printer queue: As multiple users request for a printer, then all the
requests are kept in a queue and service is based on First In First Out
Order.
 Web Server: Web Server use queue to manage incoming requests
from clients.
 Task Scheduling: Queue can be used to schedule tasks based on
priority or the order in which they were received.
 Resource Allocation : Queue can be used to manage and allocate
resources, such as printers or CPU processing time.
 Operating System : Operating System often use queue to manage
processes and resources.
4. Explain the operations performed on queue.

ENQUEUE: is used to insert a new element to the queue at


the rear end.
DEQUEUE: is used to remove one element at a time from the
front of the queue.
IS EMPTY: used to check whether the queue has any element
or not, as to avoid Underflow exception.
PEEK: used to view elements at the front of the queue, without
removing it from the queue.
IS FULL: used to check whether any more elements can be
added to the queue or not, to avoid Overflow exceptions.

5. Write a note on deque.


Deque (pronounced as “deck”) is an arrangement in which
addition and removal of element(s) can happen from any end,
i.e. head/front or tail/rear.
It is also known as Double ended queue, because it permits
insertion, deletion operations from any end.

6. Write the applications of deque.


 Storing a web brower’s history.
 Undo/Redo option in any text editor.
 To check whether a given string is palindrome or not.

7. Explain the operations performed on deque.

Operations on Deque

 INSERTFRONT: This operation is used to insert an element from


the front of the deque.
 INSERT REAR: This operation is used to insert a new element
at the rear of the deque.
 DELETION FRONT: This operation is used to delete an
element from the front of the deque.
DELETION REAR: This operation i s us ed to delete an
element from the rear of the deque.
8. Write an algorithm to check whether a string is a palindrome or
not.
Algorithm to check whether a string is a palindrome or not
using a deque.
Step1:Start traversing string from left side, a character at a
time.
Step 2:Insert the character in deque as normal queue using
INSERTREAR.
Step 3:Repeat Step 1 and Step 2 for all characters of string.
Step 4: Remove one character from the front and one character
from the rear end of deque using DELETIONFRONT a n d
DELETI ONR EAR .

Step 5: Match these two removed characters.


Step 6: If they are same then,

Then repeat steps 4 and 5 till deque is empty or left with


only one character, eventually string is a palindrome.

Else,Stop as string is not a palindrome.

You might also like