Computer Science Made by MPS
Computer Science Made by MPS
"Every syntax error is an exception but every exception cannot be a syntax error." Justify the statement.
Answer
A syntax error is a specific type of exception that is detected when we have not followed the rules of the
particular programming language while writing a program. On the other hand, an exception is a Python
object that represents any type of error or exceptional condition encountered during program execution.
This includes not only syntax errors but also runtime errors and logical errors. Therefore, every syntax error
is an exception but every exception cannot be a syntax error.
Question 2
When are the following built-in exceptions raised? Give examples to support your answers.
1. ImportError
2. IOError
3. NameError
4. ZeroDivisionError
Answer
1. ImportError — It is raised when the requested module definition is not found.
Example :
import module
Output
Output
Output
Output
Question 3
What is the use of a raise statement? Write a code to accept two numbers and display the quotient.
Appropriate exception should be raised if the user enters the second number (denominator) as zero (0).
Answer
The raise statement is used to throw an exception during the execution of a program.
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
if denominator == 0:
raise ZeroDivisionError("Error: Denominator cannot be zero.")
else:
quotient = numerator / denominator
print("Quotient:", quotient)
Output
Question 4
Use assert statement in Question No. 3 to test the division expression in the program.
Answer
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
assert denominator != 0, "Error: Denominator cannot be zero."
quotient = numerator / denominator
print("Quotient:", quotient)
Output
Question 5
Define the following:
1. Exception Handling
2. Throwing an exception
3. Catching an exception
Answer
1. Exception Handling — The process of writing additional code in a program to give proper messages
or instructions to the user upon encountering an exception is known as exception handling.
2. Throwing an exception — Throwing an exception refers to the process of creating an exception
object and passing it to the runtime system or the appropriate exception handler.
3. Catching an exception — Catching an exception refers to the process of executing a suitable
handler or block of code specifically designed to handle that particular exception when it occurs
during program execution.
Question 6
Question 7
Answer
print("Learning Exceptions...")
try:
num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
quotient = (num1 / num2)
print("Both numbers entered were correct")
except ValueError: # 1 : to enter only integers
print("Please enter only numbers")
except ZeroDivisionError: # 2 : Denominator should not be zero
print("Number 2 should not be zero")
else:
print("Great.. you are a good programmer")
finally: # 3 : to be executed at the end
print("JOB OVER... GO GET SOME REST")
Explanation
1. When using int(input("Enter the first number")) or int(input("Enter the second number")) , the user is expected
to input an integer. If the user enters a non-integer value (like a string or a floating-point number), a
ValueError will be raised during the conversion to an integer. The except ValueError: block is used to
handle this situation by displaying a message asking the user to enter only numbers.
2. In the line quotient = (num1 / num2), if num2 is entered as zero, it will lead to a ZeroDivisionError during
the division operation (num1 / num2). The except ZeroDivisionError: block is used to handle this scenario
by displaying a message informing the user that the second number should not be zero.
3. The finally: block is used to define code that should be executed regardless of whether an exception
occurs or not.
Question 8
You have learnt how to use math module in Class XI. Write a code where you use the wrong number of
arguments for a method (say sqrt() or pow()). Use the exception handling process to catch the ValueError
exception.
Answer
Note — The TypeError occurs when an incorrect number of arguments is provided for a function, while
the ValueError occurs when the number of arguments are correct but they contain inappropriate values.
Hence, in the following code TypeError is raised due to providing an incorrect number of arguments to
the math.sqrt() and math.pow() function and it is handled using except.
import math
try:
result = math.pow(2, 3, 4, 5) # pow() expects 2 arguments,
# but 4 are provided
except TypeError:
print("TypeError occurred with math.pow()")
else:
print("Result:", result)
try:
result = math.sqrt(9, 2) # sqrt() expects 1 argument,
# but 2 are provided
except TypeError:
print("TypeError occurred with math.sqrt()")
else:
print("Result:", result)
Output
TypeError occurred with math.pow()
TypeError occurred with math.sqrt()
Question 9
What is the use of finally clause ? Use finally clause in the problem given in Question No. 7.
Answer
The statements inside the finally block are always executed, regardless of whether an exception has
occurred in the try block or not. It is a common practice to use the finally clause while working with files to
ensure that the file object is closed.
print("Learning Exceptions...")
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
quotient = (num1 / num2)
print(quotient)
print("Both numbers entered were correct")
except ValueError:
print("Please enter only numbers")
except ZeroDivisionError:
print("Number 2 should not be zero")
else:
print("Great.. you are a good programmer")
finally:
print("JOB OVER... GO GET SOME REST")
Output
Learning Exceptions...
Enter the first number: 12
Enter the second number: 4
3.0
Both numbers entered were correct
Great.. you are a good programmer
JOB OVER... GO GET SOME REST
Learning Exceptions...
Enter the first number: var
Please enter only numbers
JOB OVER... GO GET SOME REST
Learning Exceptions...
Enter the first number: 33
Enter the second number: 0
Number 2 should not be zero
JOB OVER... GO GET SOME REST
Chapter 2
File Handling in Python
Exercise
Question 1(a)
A text file consists of human readable A binary file is made up of non-human readable
characters, which can be opened by any characters and symbols, which require specific
text editor. programs to access its contents.
Files with extensions like .txt, .py, .csv etc Files with extensions like .jpg, .pdf etc are some
are some examples of text files. examples of binary files.
Question 1(b)
readline() readlines()
The readline() function reads from a file in read The readlines() function, also reads from
mode and returns the next line in the file or a blank a file in read mode and returns a list of
string if there are no more lines. all lines in the file.
The returned data is of string type. The returned data is of list type.
Question 1(c)
write() writelines()
The write() method is used to write a The writelines() method is used to write multiple
single string to a file. strings to a file.
The write() method takes a string as The writelines() method takes an iterable object like
an argument. lists, tuple, etc. containing strings as an argument.
The write() method returns the number The writelines() method does not return the number
of characters written on to the file. of characters written in the file.
Question 2
1. open()
2. read()
3. seek()
4. dump()
Answer
1. open() — The open() method opens the given file in the given mode and associates it with a file
handle. Its syntax is file_object = open(file_name, access_mode) .
2. read() — The read() method is used to read data from a file object. It reads at most 'n' bytes from the
file, where 'n' is an optional parameter. If no 'n' is specified, the read() method reads the entire
contents of the file. Its syntax is: file_object.read(n).
3. seek() — This method is used to position the file object at a particular position in a file. Its syntax
is: file_object.seek(offset [, reference_point]) .
4. dump() — This method is used to convert (pickling) Python objects for writing data in a binary file. Its
syntax is : dump(data_object, file_object) .
Question 3
Write the file mode that will be used for opening the following files. Also, write the Python statements to
open the following files:
Answer
1. File Mode: 'r+'
fh = open("example.txt", "r+")
2. File Mode: 'wb'
fh = open("bfile.dat", "wb")
3. File Mode: 'a+'
fh = open("try.txt", "a+")
4. File Mode: 'rb'
fh = open("btry.dat", "rb")
Question 4
Why is it advised to close a file after we are done with the read and write operations? What will happen if
we do not close it ? Will some error message be flashed ?
Answer
It is a good practice to close a file once we are done with the read and write operations. When we close a
file, the system frees the memory allocated to it. Python ensures that any unwritten or unsaved data is
flushed (written) to the file before it is closed. Therefore, it is always advised to close the file once our work
is done. If we do not close file explicitly it will close automatically later when it's no longer in use or when
the program terminates, without displaying any error message.
Question 5
What is the difference between the following set of statements (a) and (b):
(a)
P = open("practice.txt", "r")
P.read(10)
(b)
with open("practice.txt", "r") as P:
x = P.read()
Answer
The code given in (a) will open file "practice.txt" in read mode and will read 10 bytes from it. Also, it will not
close the file explicitly. On the other hand, the code given in (b) will open file "practice.txt" in read mode
and will read the entire content of the file. Furthermore, it will automatically close the file after executing the
code due to the with clause.
Question 6
Write a command(s) to write the following lines to the text file named hello.txt. Assume that the file is
opened in append mode.
“ Welcome my class”
“It is a fun place”
“You will learn and play”
Answer
file = open("hello.txt", "a")
lines = [
"Welcome my class\n",
"It is a fun place\n",
"You will learn and play"
]
file.writelines(lines)
file.close()
Question 7
Write a Python program to open the file hello.txt used in question no 6 in read mode to display its contents.
What will be the difference if the file was opened in write mode instead of append mode?
Answer
f = open("hello.txt", "r")
st = " "
while st:
st = f.readlines()
print(st)
f.close()
If the file "hello.txt" was opened in write mode instead of append mode, it would have overwritten the
existing content of the file. In write mode ("w"), opening the file truncates its content if it already exists and
starts writing from the beginning. Therefore, the previous contents of the file would have been replaced
with the new lines provided in the write mode code snippet.
Question 8
Write a program to accept string/sentences from the user till the user enters “END” to. Save the data in a
text file and then display only those sentences which begin with an uppercase alphabet.
Answer
f = open("new.txt", "w")
while True:
st = input("Enter next line:")
if st == "END":
break
f.write(st + '\n')
f.close()
f = open("new.txt", "r")
while True:
st = f.readline()
if not st:
break
if st[0].isupper():
print(st)
f.close()
Output
Enter next line:Hello world
Enter next line:welcome to
Enter next line:Python programming
Enter next line:END
Hello world
Python programming
Question 9
Question 10
Output
How many records to be entered? 5
Enter item no: 11
Enter item name: Mobile
Enter quantity: 4
Enter price: 20000
Enter item no: 12
Enter item name: Laptop
Enter quantity: 2
Enter price: 35000
Enter item no: 13
Enter item name: Computer
Enter quantity: 1
Enter price: 50000
Enter item no: 14
Enter item name: Television
Enter quantity: 4
Enter price: 25000
Item No: 11
Item Name: Mobile
Quantity: 4
Price per item: 20000.0
Amount: 80000.0
Item No: 12
Item Name: Laptop
Quantity: 2
Price per item: 35000.0
Amount: 70000.0
Item No: 13
Item Name: Computer
Quantity: 1
Price per item: 50000.0
Amount: 50000.0
Item No: 14
Item Name: Television
Quantity: 4
Price per item: 25000.0
Amount: 100000.0
Stack
Class 12 - NCERT Computer Science Solutions
Exercise
Question 1
(d) In POSTFIX notation for expression, operators are placed after operands.
Answer
(a) True
Reason — A stack is a linear data structure following the Last In, First Out (LIFO) principle, where elements are arranged sequentially.
(b) False
Reason — A stack follows the Last In, First Out (LIFO) rule. In a stack, the last element added is the first one to be removed from the stack.
(c) False
Reason — When attempting to remove an element (POP operation) from an empty stack, it leads to an underflow condition, resulting in an
exception being raised.
(d) True
Reason — In POSTFIX notation for expression, operators are placed after the corresponding operands.
Question 2(a)
result = 0
numberList = [10, 20, 30]
numberList.append(40)
result = result + numberList.pop()
result = result + numberList.pop()
print("Result=", result)
Answer
Output
Result= 70
Explanation
The code initializes result to 0 and creates a list [10, 20, 30]. It appends 40 to the list and then performs two pop() operations on the list, which
removes and returns the last element (40 and 30). These values are added to result, resulting in result being 70. Finally, the code prints
"Result=" followed by the value of result, which is 70.
Question 2(b)
Output
Result= MAT
Explanation
The code initializes an empty list answer and an empty string output. It appends the characters 'T', 'A', and 'M' to the answer list. After
appending, answer list becomes ['T', 'A', 'M'].
After that, three pop() operations are performed on answer, removing and returning the last element each time ('M', 'A', and 'T' respectively).
These characters are concatenated to the output string. So, output string becomes MAT which is printed as the final output.
Question 3
Answer
def reverse(string):
n = len(string)
stack = []
for i in range(n):
push(stack, string[i])
string = ""
for i in range(n):
string += pop(stack)
return string
Output
Question 4
((2 + 3) * (4 / 2)) + 2
Show step-by-step process for matching parentheses using stack data structure.
Answer
For matching parentheses, we can push in the stack for each opening parenthesis of the expression and pop from the stack for each closing
parenthesis.
( ↑ — top
( Push
↑
((
( Push
↑
2 ..........
+ ..........
3 ..........
) ( Pop
↑
* ..........
((
( Push
↑
4 ..........
/ ..........
2 ..........
(
) Pop
↑
) #Empty Pop
+ ..........
2 #Empty ..........
Evaluate following postfix expression while showing status of stack after each operation given A = 3, B = 5, C = 1, D = 4.
AB + C *
Answer
AB + C * = 35 + 1 *
Intermediate
Symbol Action Stack
output
3
3 Push
↑
53
5 Push
↑
#Empty
+ Pop twice and Evaluate and Push back 3+5=8
8
↑
18
1 Push
↑
#Empty
Hence, AB + C * = 35 + 1 * = 8
Question 5(b)
Evaluate following postfix expression while showing status of stack after each operation given A = 3, B = 5, C = 1, D = 4.
AB * C / D *
Answer
AB * C / D * = 35 * / 4 *
3 Push 3
53
5 Push
↑
#Empty
1 15
1 Push
↑
#Empty
↑
4 15
4 Push
↑
#Empty
Hence, AB * C / D * = 35 * / 4 * = 60
Question 6(a)
Convert the following infix notation to postfix notation, showing stack and string contents at each step.
A+B-C*D
Answer
Given,
A+B-C*D
Postfix
Symbol Action Stack
Expression
A
+ A
+ Push in stack
↑
B AB
-
- Equal precedence to +. Pop from stack, add in expression then push this operator(-) AB+
↑
*- AB+C
* Higher precedence than (-), hence Push
↑
D AB+CD
Question 6(b)
Convert the following infix notation to postfix notation, showing stack and string contents at each step.
A * (( C + D)/E)
Answer
Given,
A * (( C + D)/E)
*
* Push
↑
(* A
( Push
↑
((*
( Push
↑
C
+((* 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 add popped operator to expression ACD+E/
↑
Write a program to create a Stack for storing only odd numbers out of all the numbers entered by the user. Display the content of the Stack along
with the largest odd number in the Stack. (Hint. Keep popping out the elements from stack and maintain the largest element retrieved so far in a
variable. Repeat till Stack is empty)
Answer
def pop(stack):
if stack == []:
return
return stack.pop()
def oddStack(num):
if num % 2 == 1:
push(stack, num)
def GetLargest(stack):
elem = pop(stack)
large = elem
while elem != None:
if large < elem:
large = elem
elem = pop(stack)
return large
Output
Question 1
(a) ............... is a linear list of elements in which insertion and deletion takes place from different ends.
(c) Insertion operation in a queue is called ............... and deletion operation in a queue is called ............... .
(e) Elements 'A', 'S', 'D' and 'F' are present in the queue, and they are deleted one at a time, ............... is the sequence of element received.
(f) ............... is a data structure where elements can be added or removed at either end, but not in the middle.
(g) A deque contains 'z', 'x', 'c', 'v' and 'b' . Elements received after deletion are 'z', 'b', 'v', 'x' and 'c'. ............... is the sequence of deletion
operation performed on deque.
Answer
(a) Queue
(b) FIFO
(d) front
(f) Deque
(g)
deletionFront()
deletionRear()
deletionRear()
deletionFront()
deletionFront()
Question 2
Answer
Stack Queue
Stack follows LIFO (Last in First out) principle. Queue follows FIFO (First in First out) principle.
In stack, Push operation is used for element insertion and Pop In queue, enqueue is used for element insertion and dequeue
operation is used for element deletion. is used for element deletion.
Question 3
Answer
FIFO, First In First Out, defines a queue because in a queue, elements are retrieved from one end (called the front end) and inserted at another
end (rear end). Thus, at any time, in a queue, retrieval gets the oldest element, while always adding to the rear of the queue. Thus, items are
processed in first-in, first-out (FIFO) order.
Question 4
Write a menu driven python program using queue, to implement movement of shuttlecock in it's box.
Answer
queue = []
def display_queue():
if not queue:
print("Queue is empty")
else:
print("Current queue:", queue)
def enqueue(item):
queue.append(item)
def dequeue():
if queue:
removed = queue.pop(0)
print("Removed", removed, "from the queue")
else:
print("Queue is empty, cannot remove")
while True:
print("\nMENU:")
print("1. Add movement to the queue")
print("2. Remove movement from the queue")
print("3. Display current queue")
print("4. Exit")
if choice == '1':
movement = input("Enter the movement (up/down): ")
enqueue(movement)
print("Added", movement, "to the queue")
elif choice == '2':
dequeue()
elif choice == '3':
display_queue()
elif choice == '4':
print("Exiting program...")
break
else:
print("Invalid choice, please try again")
Output
MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 1
Enter the movement (up/down): up
Added up to the queue
MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 1
Enter the movement (up/down): down
Added down to the queue
MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 3
Current queue: ['up', 'down']
MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 2
Removed up from the queue
MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 3
Current queue: ['down']
MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 4
Exiting program...
Question 5
Queues only allow insertion in one end (rear end) and retrieval from the other end (front end). A deque, on the other hand, is a double-ended
queue, which allows flexibility with insertion or deletion such that one of these operations is allowed at both ends rather than having a fixed end
for the operations.
Question 6
enqueue(34)
enqueue(54)
dequeue()
enqueue(12)
dequeue()
enqueue(61)
peek()
dequeue()
dequeue()
dequeue()
dequeue()
enqueue(1)
Answer
34
enqueue(34) ↑↑
fr
34 54
enqueue(54) ↑ ↑
f r
54
dequeue() ↑↑
fr
54 12
enqueue(12) ↑ ↑
f r
12
dequeue() ↑↑
fr
12 61
enqueue(61) ↑ ↑
f r
Peek() 12
61
dequeue() ↑↑
fr
dequeue() #Empty
dequeue() underflow
dequeue() underflow
1
enqueue(1)
↑↑
fr
Question 7
peek()
insertFront(12)
insertRear(67)
deletionFront()
insertRear(43)
deletionRear()
deletionFront()
deletionRear()
Answer
peek() #Empty
12
insertFront(12) ↑↑
fr
insertRear(67) 12 67
↑ ↑
f r
67
deletionfront() ↑↑
fr
67 43
insertRear(43) ↑ ↑
f r
67
deletionRear() ↑↑
fr
deletionfront() #Empty
deletionRear() Underflow
Question 8
Write a python program to check whether the given string is palindrome or not, using deque. (Hint : refer to algorithm 4.1)
Answer
def Deque():
return []
def removeFront(deque):
if len(deque) == 0:
return None
return deque.pop(0)
def removeRear(deque):
if len(deque) == 0:
return None
return deque.pop()
def palchecker(aString):
chardeque = Deque()
for ch in aString:
addRear(chardeque, ch)
while len(chardeque) > 1:
first = removeFront(chardeque)
last = removeRear(chardeque)
if first != last:
return False
return True
Output