You are on page 1of 23

MODEL QUESTION PAPER 2 SOLUTIONS

MODULE 1
1a With Python programming examples to each, explain the syntax and control flow diagrams of break
and continue statements.
break Statement

✓ The break statement is used to immediately exit from the loop.


✓ A break statement simply contains the break keyword.

✓ The first line ❶ creates an infinite loop; it is a while loop whose condition is always
True.
✓ The program execution will always enter the loop and will exit it only when a break
statement isexecuted.
✓ The program asks the user to type name ❷.
✓ While the execution is still inside the while loop, an if statement gets executed ❸
to checkwhether name is equal to entered name.
✓ If this condition is True, the break statement is run ❹, and the execution moves out
of the loopto print('Thank you!') ❺.

continue Statement
✓ The continue statement is used to immediately jump back to the start of the loop and
reevaluatethe loop‟s condition.
✓ A continue statement simply contains continue keyword.

✓ If the user enters any name besides Joe ❶, the continue statement ❷ causes the
programexecution to jump back to the start of the loop.
✓ When it reevaluates the condition, the execution will always enter the loop, since the
condition issimply the value True. Once they make it past that if statement, the user is
asked for a password
❸.
If the password entered is swordfish, then the break statement ❹ is run, and the
execution jumpsout of the while loop to print Access granted ❺.
b Explain TWO ways of importing modules into application in Python with syntax and suitable 6
programming examples.

➢ All Python programs can call a basic set of functions called built-in functions,
including the print(), input(), and len() functions.
➢ Python also comes with a set of modules called the standard library.
➢ Before we can use the functions in a module, we must import the module with an
import statement. In code, an import statement consists of the following:
1. The import keyword
2. The name of the module
3. Optionally, more module names, as long as they are separated by commas
➢ Example with output:

➢ The random.randint() function call evaluates to a random integer value between the
two integers that you pass it.
➢ Since randint() is in the random module, we must first type random. in front of the
function name to tell Python to look for this function inside the random module.
➢ Here‘s an example of an import statement that imports four different modules:

from import Statements


➢ An alternative form of the import statement is composed of the from keyword,followed
by the module name, the import keyword, and a star; for example, from random import *.
➢ With this form of import statement, calls to functions in random will not need the
random prefix.
➢ However, using the full name makes for more readable code, so it is better to use the
normal form of the import statement.

c Write a function to calculate factorial of a number. Develop a program to 6


compute binomialcoefficient (Given N and R).
def factorial (n):
if n==0:
return 1
else:
return n*factorial(n-1)
n=int(input(‘input a number to compute the factorial”))
print(factorial(n))
OUTPUT:
Input a number to compute the factorial:3
6
2a Explain looping control statements in Python with a syntax and example to 6
each.
There are four types of flow control statements:
1. if Statement
2. else Statement
3. elif Statement
1. if Statements:
➢ An if statement‟s clause (that is, the block following the if statement) will
execute if thestatement‟s condition is True. The clause is skipped if the condition
is False.
➢ In plain English, an if statement could be read as, “If this condition is true, execute the
code in theclause.”
➢ In Python, an if statement consists of the following:
1. The if keyword
2. A condition (that is, an expression that evaluates to True or False)
3. A colon
4. Starting on the next line, an indented block of code (called the if clause)
➢ Example:

➢ Flowchart:

2. else Statements:

➢ An if clause can optionally be followed by an else statement. The else clause is


executed onlywhen the if statement‟s condition is False.
➢ In plain English, an else statement could be read as, “If this condition is true, execute
this code.Or else, execute that code.”
➢ An else statement doesn‟t have a condition, and in code, an else statement always
consists of thefollowing:
1. The else keyword
2. A colon
3. Starting on the next line, an indented block of code (called the else clause)
➢ Example:
➢ Flowchart:

3. elif Statements:

➢ If we have more than one condition then elif statement is used.


➢ The elif statement is an “else if” statement that always follows an if or another elif
statement.
➢ It provides another condition that is checked only if all of the previous conditions
were False.
➢ In code, an elif statement always consists of the following:
1. The elif keyword
2. A condition (that is, an expression that evaluates to True or False)
3. A colon
4. Starting on the next line, an indented block of code (called the elif clause)

➢ Flowchart:
➢ Example:

2b Develop a Python program to generate Fibonacci sequence of length (N). Read 4


N from the console.
def fibonacci(n):
if n< 0:
print("incorrect input")
elif n==1:
return 0
elif n==2:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
n=int(input("Enter the value of N"))
if n>0:
x = fibonacci(n)
print(x)
else:
print("Enter the correct values")
2c Write a function named DivExp which takes TWO parameters a, b and returns 6
a value c (c=a/b). Write suitable assertion for a>0 in function DivExp and raise
an exception for when b=0.
Develop a Python program which reads two values from the console and calls a
function DivExp.
Def DivExp():
try:
a=int(input(“enter an integer:”))
b=int(input(“enter another integer”))
c=a/b
except ZeroDivisionError:
c=”you cannot divide by 0”
print(c)
DivExp()

OUTPUT:
Enter an integer :10
Enter another integer:5
2.0

2d Explain Local and Global Scope in Python programs. What are local and global variables? 4
How can youforce a variable in a function to refer to the global variable?
✓ Parameters and variables that are assigned in a called function are said to
exist in thatfunction‟s local scope.
✓ Variables that are assigned outside all functions are said to exist in the global scope.
✓ A variable that exists in a local scope is called a local variable, while a variable that
exists in theglobal scope is called a global variable.
✓ Scopes matter for several reasons:
1. Code in the global scope cannot use any local variables.
2. However, a local scope can access global variables.
3. Code in a function‟s local scope cannot use variables in any other local scope.
4. We can use the same name for different variables if they are in different scopes.
That is, therecan be a local variable named spam and a global variable also named
spam.
✓ We can force a variable in a function to refer to the global variable using global
statement asshown below:

Program Output

✓ Because eggs is declared global at the top of spam() ❶, when eggs is set to
'spam' ❷, thisassignment is done to the globally scoped eggs. No local eggs variable
is created.
MODULE 2
3a Explain with a programming example to each: 6
(ii) get()
(iii) setdefault()
(i) get( ): Dictionaries have a get() method that takes two arguments:
➢ The key of the value to retrieve
➢ A fallback value to return if that key does not exist.

The setdefault() Method


➢ To set a value in a dictionary for a certain key only if that key does not already have a
value.

➢ The setdefault() method offers a way to do this in one line of code.


➢ Setdeafault() takes 2 arguments:
o The first argument is the key to check for, and
o The second argument is the value to set at that key if the key does not
exist. If the key does exist, the setdefault() method returns the key’s value.

The first time setdefault() is called, the dictionary in spam changes to {'color': 'black','age':
5, 'name': 'Pooka'}. The method returns the value 'black' because this is now the value set
for the key 'color'. When spam.setdefault('color', 'white') is called next, the value for that
key is not changed to 'white' because spam already has a key named 'color'.
Ex: program that counts the number of occurrences of each letter in a string.

OUTPUT:
3b Develop suitable Python programs with nested lists to explain copy.copy( ) and 8
copy.deepcopy( ) methods.
Copy module must be imported and can be used to make a duplicate copy of a mutable
value like a list or dictionary, not just a copy of a reference.

copy.copy( ): A shallow copy creates a new object which stores the reference of the original
elements.So, a shallow copy doesn't create a copy of nested objects, instead it just copies the
referenceof nested objects. This means, a copy process does not create copies of nested
objects itself.

Example:

import copy
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.copy(old_list)
old_list[1][1] = 'AA'
print("Old list:", old_list)
print("New list:", new_list)
Output:
Old list: [[1, 1, 1], [2, 'AA', 2], [3, 3, 3]]
New list: [[1, 1, 1], [2, 'AA', 2], [3, 3, 3]]

copy.deepcopy( ): A deep copy creates a new object and recursively adds the copies of nested
objects present in the original elements.
Example:
import copy
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.deepcopy(old_list)
old_list[1][0] = 'BB'
print("Old list:", old_list)
print("New list:", new_list)
Output:
Old list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]]
New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]

3c Explain append() and index() functions with respect to lists in Python. 6


Finding a Value in a List with the index() Method
➢ List values have an index() method that can be passed a value, and if that value exists in
the list, the index of the value is returned. If the value isn’t in the list, then Python produces
a ValueError error.

➢ When there are duplicates of the value in the list, the index of its first appearance is
returned.
➢ The append() method call adds the argument to the end of the list.

➢ The append() and insert() methods are list methods and can be called only on list values,
not on other values such as strings or integers.

4a Explain different ways to delete an element from a list with suitable Python 10
syntax and programming examples.

• The remove() method is passed the value to be removed from the list it is called
on.

➢ Attempting to delete a value that does not exist in the list will result in a ValueError
error.

➢ If the value appears multiple times in the list, only the first instance of the value will
be removed.

➢ The del statement is good to use when you know the index of the value you want to
remove from the list. The remove() method is good when you know the value you
want to remove from the list.
4b Read a multi-digit number (as chars) from the console. Develop a program to 6
print the frequency of each digit with suitable message.

n=int(input(“enter any number”))


print(“Digit\t frequency”)
for I in range(0,10):
count=0
temp=n
while temp>0:
digit=temp%10
if digit==i:
count=count+1
temp=temp//10
if count>0:
print(I,”\t”,count)

OUTPUT:
Enter any number:66757733
Digit Frequency
3 2
5 1
6 2
7 3

4c Tuples are immutable. Explain with Python programming example. 4


Tuples are basically a data type in python, We can also define tuples as lists that we cannot change.
Therefore, we can call them immutable tuples. Hence, tuples are not modifiable in nature. These
immutable tuples are a kind of group data type.

Example 1: Tuple with integers as elements

>>>tup = (22, 33, 5, 23)

>>>tup

(22, 33, 5, 23)

Example 2: Tuple with mixed data type

>>>tup2 = (‘hi’, 11, 45.7)

>>>tup2

(‘hi’, 11, 45.7)

Immutable Tuples

>>>tuple1 = (1, 2, 33, 44, 6)

>>>tuple1[4] = 10

Type Error: ‘tuple’ object does not support item assignment

MODULE-3
5a Explain Python string handling methods with examples: split(), endswith(), ljust(), center(),
lstrip()

➢ The split() method is called on a string value and returns a list of strings.

➢ We can pass a delimiter string to the split() method to specify a different string to split 10
upon.

➢ The startswith() and endswith() methods return True if the string value they are
called on begins or ends (respectively) with the string passed to the method;
otherwise, they return False.

➢ The rjust() and ljust() string methods return a padded version of the string they are
called on, with spaces inserted to justify the text.
➢ The first argument to both methods is an integer length for the justified string.

➢ ‘Hello’.rjust(10) says that we want to right-justify ‘Hello’ in a string of total length 10.
‘Hello’ is five characters, so five spaces will be added to its left, giving us a string of
10 characters with ‘Hello’ justified right.
➢ An optional second argument to rjust() and ljust() will specify a fill character other
than a space character.

➢ The center() string method works like ljust() and rjust() but centers the text rather than
justifying it to the left or right.

5b Explain reading and saving python program variables using shelve module with suitable Python
program

✓ The variables can be saved in Python programs to binary shelf files using the shelve
module.
✓ This helps the program to restore data to variables from the hard drive.
✓ The shelve module will let us add Save and Open features to your program.
✓ Example:

06

5c Develop a Python program to read and print the contents of a text file
>>> baconFile = open(‘bacon.txt’, ‘w’)
>>> baconFile.write(‘Hello world!\n’)
13
>>> baconFile.close()
>>> baconFile = open(‘bacon.txt’, ‘a’)
>>> baconFile.write(‘Bacon is not a vegetable.’) 25
>>> baconFile.close()
>>> baconFile = open(‘bacon.txt’)
>>> content = baconFile.read() >>> baconFile.close() 04
>>> print(content)
Hello world!
Bacon is not a vegetable
Explain Python string handling methods with examples: join(), startswith() ,rjust(), strip(), rstrip()

➢ The join() method is useful when we have a list of strings that need to be joined
together into a single string value.
6a ➢ The join() method is called on a string, gets passed a list of strings, and returns a string.
The returned string is the concatenation of each string in the passed-in list.

➢ The startswith() and endswith() methods return True if the string value they are
called on begins or ends (respectively) with the string passed to the method;
10
otherwise, they return False.

➢ The rjust() and ljust() string methods return a padded version of the string they are
called on, with spaces inserted to justify the text.
➢ The first argument to both methods is an integer length for the justified string.

➢ The strip() string method will return a new string without any whitespace characters at
the beginning or end.
➢ The lstrip() and rstrip() methods will remove whitespace characters from the left and
right ends, respectively.
6b Explain with suitable Python program segments: (i) os.path.basename() (ii)os.path.join()

✓ Calling os.path.basename(path) will return a string of everything that comes after the
last slash inthe path argument.

➢ Example:
05

The Python os.path.join method combines path names into one complete path. This means
that we can merge multiple parts of a path into one using the os.path.join method instead
of hard-coding every pathname manually.
Import os
path = “/Home”
combined_path = os.path.join(path, “tutorials”, “main_file.py”)
print(combined_path)

6c) Develop a Python program find the total size of all the files in the given directory

# import module
import os
# assign size
size = 0
# assign folder path
Folderpath = ‘C:/Users/Geetansh Sahni/Documents/R’
# get size
for path, 14irs., files in os.walk(Folderpath):
for f in files:
fp = os.path.join(path, f)
size += os.path.getsize(fp) 05
# display size
print(“Folder size: “ + str(size))

MODULE-4
7a) Explain permanent delete and safe delete with a suitable Python programming example to each
You can delete a single file or a single empty folder with functions in the os module,
whereas to delete a folder and all of its contents, you use the shutil module.

• Calling os.unlink(path) will delete the file at path.


• Calling os.rmdir(path) will delete the folder at path. This folder must be
empty of any files or folders.
• Calling shutil.rmtree(path) will remove the folder at path, and all files
and folders it contains will also be deleted

import os
for filename in os.listdir():
if filename.endswith('.rxt'):
os.unlink(filename)

Since Python’s built-in shutil.rmtree() function irreversibly deletes files and folders, it can
be dangerous to use. A much better way to delete files and folders is with the third-party
send2trash module

import send2trash
>>> baconFile = open('bacon.txt', 'a') # creates the file
>>> baconFile.write('Bacon is not a vegetable.')
25
>>> baconFile.close()
>>> send2trash.send2trash('bacon.txt')
08
7b) Develop a program to backing Up a given Folder (Folder in a current working directory) into a ZIP
File by using relevant modules and suitable methods

import os
import zipfile

zf = zipfile.ZipFile("myzipfile.zip", "w")
for dirname, subdirs, files in os.walk("mydirectory"):
zf.write(dirname)
for filename in files:
zf.write(os.path.join(dirname, filename))
zf.close()

7c)
Explain the role of Assertions in Python with a suitable program

✓ Assertion: An assertion is a sanity check to make sure the code isn‟t doing something
obviouslywrong.
✓ If the sanity check fails, then an Assertion Error exception is raised. 06
✓ In python, an assert statement consists of the following:
1. The assert keyword
2. A condition (that is, an expression that evaluates to True or False)
3. A comma
4. A string to display when the condition is False
✓ In plain English, an assert statement meaning is, “I assert that this condition holds true,
and if not,there is a bug somewhere in the program.”

Here is a function that converts a temperature from degrees Kelvin to degrees Fahrenheit.
Since zero degrees Kelvin is as cold as it gets, the function bails out if it sees a negative
temperature

def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32

print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)

Explain the functions with examples: (i) shutil.copytree() (ii) shutil.move()(iii) shutil.rmtree().
8a)
Copy: shutil.copy(source, destination) will copy the file from source path to destination 06
path.

In the above example:


1 → Destination is a folder, hence the source file is copied to destination file.
2 → Destination is a folder with a filename, hence the source file copied will be
renamed to thegiven filename.

Move: shutil.move(source, destination) will move the file or folder from source path to the
destinationpath and will return a string of the absolute path of the new location.

Rename: shutil.move(source, destination) can be used to move and rename also.

Delete: We can delete a single file or a single empty folder with functions in the os
module, whereasto delete a folder and all of its contents, we use the shutil module.
1. Calling os.unlink(path) will delete the file at path.
2. Calling os.rmdir(path) will delete the folder at path. This folder must be empty of
any files orfolders.
3. Calling shutil.rmtree(path) will remove the folder at path, and all files and folders
it containswill also be deleted.

Ex: import os
for filename in in os.listdir( ):
if filename.endswith(„.txt‟):
os.unlink(filename)
8b)
Develop a Python program to traverse the current directory by listing subfolders and
files

import os
for folderName, subfolders, filenames in os.walk('C:\\delicious'):
print('The current folder is ' + folderName)
for subfolder in subfolders:
06
print('SUBFOLDER OF ' + folderName + ': ' + subfolder)

for filename in filenames:


print('FILE INSIDE ' + folderName + ': '+ filename)
print('')

8c) Explain the support for Logging with logging module in Python

Logging
➢ Logging is a great way to understand what’s happening in your program and in what order its
happening.
➢ Python’s logging module makes it easy to create a record of custom messages that you write.
➢ These log messages will describe when the program execution has reached the logging function call
and list any variables you have specified at that point in time.
➢ On the other hand, a missing log message indicates a part of the code was skipped and never
executed.
Using the logging Module
➢ To enable the logging module to display log messages on your screen as your program runs,
➢ when Python logs an event, it creates a LogRecord object that holds information about that event.
➢ The logging module’s basicConfig() function lets you specify what details about the
LogRecord object you want to see and how you want those details displayed.

With the logging module imported, you can use something called a “logger” to log messages 08
that you want to see. By default, there are 5 standard levels indicating the severity of events.
Each has a corresponding method that can be used to log events at that level of severity. The
defined levels, in order of increasing severity, are the following:
DEBUG
INFO
WARNING
ERROR
CRITICAL

The logging module provides you with a default logger that allows you to get started without
needing to do much configuration. The corresponding methods for each level can be called as
shown in the following example:
import logging
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')

9a Explain the methods __init__ and __str__ with suitable code example to each

init : The init method (short for “initialization”) is a special method that gets invoked
when anobject is instantiated. The parameters of init to have the same names as the
attributes.

06

str : It is a special method which returns a string representation of an object.

When we print an object, Python invokes the str method:

9b) Explain the program development concept ‘prototype and patch’ with suitable example.
The development plan I am demonstrating is called “prototype and patch”. For each function, I wrote
a prototype that performed the basic calculation and then tested it, patching errors along the way.
This approach can be effective, especially if you don’t yet have a deep understanding of the problem.
06
But incremental corrections can generate code that is unnecessarily complicated—since it deals with
many special cases—and unreliable—since it is hard to know if you have found all the errors.
An alternative is designed development, in which high-level insight into the problem can make the
programming much easier. In this case, the insight is that a Time object is really a three-digit number
in base 60 (see http://en.wikipedia.org/wiki/Sexagesimal). The second attribute is the “ones column”,
the minute attribute is the “sixties column”, and the hour attribute is the “thirty-six hundreds column”.
When we wrote add_time and increment, we were effectively doing addition in base 60, which is why
we had to carry from one column to the next.
This observation suggests another approach to the whole problem—we can convert Time objects to
integers and take advantage of the fact that the computer knows how to do integer arithmetic.
Here is a function that converts Times to integers:
def time_to_int(time):
minutes = time.hour * 60 + time.minute
seconds = minutes * 60 + time.second
return seconds
And here is a function that converts an integer to a Time (recall that divmod divides the first
argument by the second and returns the quotient and remainder as a tuple).
def int_to_time(seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time
You might have to think a bit, and run some tests, to convince yourself that these functions are
correct. One way to test them is to check that time_to_int(int_to_time(x)) == x for many values of x.
This is an example of a consistency check.
Once you are convinced they are correct, you can use them to rewrite add_time:
def add_time(t1, t2):
seconds = time_to_int(t1) + time_to_int(t2)
return int_to_time(seconds)

9c) Define a function which takes TWO objects representing complex numbers and returns
new complex number with a addition of two complex numbers. Define a suitable class
‘Complex’ to represent the complex number. Develop a program to read N (N >=2)
complex numbers and to compute the addition of N complex numbers.

class Complex ():


def initComplex(self):
self.realPart = int(input("Enter the Real Part: "))
08
self.imgPart = int(input("Enter the Imaginary Part: "))

def display(self):
print(self.realPart,"+",self.imgPart,"i", sep="")

def sum(self, c1, c2):


self.realPart = c1.realPart + c2.realPart
self.imgPart = c1.imgPart + c2.imgPart

c1 = Complex( )
c2 = Complex( )
c3 = Complex( )

print("Enter first complex number")


c1.initComplex()
print("First Complex Number: ", end="")
c1.display( )

print("Enter second complex number")


c2.initComplex( )
print("Second Complex Number: ", end="")
c2.display( )

print("Sum of two complex numbers is ", end="")


c3.sum(c1,c2)
c3.display( )

OUTPUT:

Enter first complex number


Enter the Real Part: 8
Enter the Imaginary Part: 4
First Complex Number: 8+4i
Enter second complex number
Enter the Real Part: 9
Enter the Imaginary Part: 7
Second Complex Number: 9+7i
Sum of two complex numbers is 17+11i

10a)
Explain the following with syntax and suitable code snippet: i) Class definition ii)
instantiation iii) passing an instance (or objects) as an argument iv) instances as return
values
Class is a abstract data type which can be defined as a template or blueprint that describes
the behavior / state that the object of its type support
10
class Point:
"""Represents a point in 2-D space."""
✓ The header indicates that the new class is called Point.
✓ The body is a docstring that explains what the class is for. You can define variables
and methodsinside a class definition.
✓ The process of creating this object is called instantiation
✓ Class can be used to create new object instances (instantiation) of that class.

The class members are accessed using dot operator as shown below:
class Point:
“ “ “ Represents a point in 2-D space “ “ “blank = Point( )
blank.x = 10
blank.y =20

Instances as return values


Functions can return instances. For example, find_center takes a Rectangle as an argument and
returns a Point that contains the coordinates of the center of the Rectangle
def find_center(rect):
p = Point()
p.x = rect.corner.x + rect.width/2
p.y = rect.corner.y +
rect.height/2return p

10b) Define pure function and modifier. Explain the role of pure functions and modifiers in
application development with suitable python programs.

Modifiers: It modifies the objects passed to it as arguments and it has effect.

Ex: In the below example the object start has been passed as parameters and it has been
changed byadding seconds to it. Hence, it is a modifier.

10
The first line performs the basic operation; the remainder deals with the special cases we saw
before.

➢ Is this function correct? What happens if seconds is much greater than sixty?
➢ In that case, it is not enough to carry once; we have to keep doing it until time. second
is less than sixty.
➢ One solution is to replace the if statements with while statements. That would make the
function correct, but not very efficient.
➢ Anything that can be done with modifiers can also be done with pure functions.

Pure Function: It does not modify any of the objects passed to it as arguments and it has
no effect,like displaying a value or getting user input, other than returning a value.

Ex: In the below example the two objects start and duration have been passed as
parameters tofunction add_time and it doesn‟t modify the objects received. Hence, it
is a pure function.

1. The result, 11:20:00 might not be what you were hoping for.
2. The problem is that this function does not deal with cases where the number of seconds or
minutes adds up to more than sixty.
➢ When that happens, we have to “carry” the extra seconds into the minute column or the
extra minutes into the hour column.

You might also like