Python Model QP Solutions
Python Model QP 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 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:
➢ Flowchart:
2. else Statements:
3. elif Statements:
➢ Flowchart:
➢ Example:
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 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]]
➢ 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.
OUTPUT:
Enter any number:66757733
Digit Frequency
3 2
5 1
6 2
7 3
>>>tup
>>>tup2
Immutable Tuples
>>>tuple1[4] = 10
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.
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.
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.
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)
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
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.
def display(self):
print(self.realPart,"+",self.imgPart,"i", sep="")
c1 = Complex( )
c2 = Complex( )
c3 = Complex( )
OUTPUT:
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
10b) Define pure function and modifier. Explain the role of pure functions and modifiers in
application development with suitable python programs.
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.