PPS Paper Solution
PPS Paper Solution
Q1) a) What is function? Write its two advantages. Explain with example Docstring. [6]
Function:
Functions are group of statements that are bundled together to perform a specific
task. Functions provide an incredibly unique aspect of programming called as modularity.
__________(1 Mark)
Advantages: (Each advantage 1 Mark / max 2 advantages)
1. To provide the readability of the code
2. Provides the facility of the reusability of the code, same function can be used in any
program rather than writing the same code from scratch.
3. Reduces the size of the code, duplicate set of statements are replaced by function calls.
Docstring: (1 Mark for definition, 2 Marks for code or example)
There is a special type of comment that is called as documentation string i.e.
docstrings as shown in below example. Generally docstrings are defined by triple double
quotes.
def add(a,b):
“““ This is a docstring. Function is defined for addition of two numbers”””
C=a+b
Print(“Addition = ”, C)
b) Explain any two standard libraries/modules from following
i. Math Module
ii. Random Module
iii. Matplotlib and pyplot
iv. Numpy
v. Date and time module [6]
(1 Marks each for correct points)
i. Math Module:
Math module is python library which supports various mathematical operations
such as ceil, floor etc. __________ (1 Mark)
a. Ceil operation using math module: This operation returns the ceiling or the
upper value of x as integer.
import math as mp
mp.ceil (1.5) __________(1 Mark)
o/p: 2
b. Floor Operation using math module: This operation returns the floor or the
lower value of x as integer.
import math as mp
mp.floor (1.5)
__________(1 Mark)
o/p: 1
ii. Random Module:
a. This module is pseudo random number generator. __________(1 Mark)
b. The randint function is used to return any random integer between the given
range such as given below example. __________(1 Mark)
import datetime
x = datetime.datetime.now()
print(x)
Ouput:
2022-07-23 20:38:13.350780
c) Write a python program using function which accepts a number as argument and
returns square of it. [6]
Answer: (6 Marks for correct program with o/p)
a = int (input(“ Enter a number to make its square: “))
def square (a):
print (“The square of number is: ”, a)
As from above you can see that at the time of calling the function arguments we have
called them by using their names. Such as child1 = “Emil”.
b) Write python program using function to find whether number is odd or even. [6]
Answer:
a = int (input(“ Enter a number to check is it even or odd? : “))
def even_odd ():
if a%2 == 0:
print(“ Number is Even”)
else:
print(“ Number is Odd”)
o/p: Enter a number to check is it even or odd? : 5
Number is Odd
c) Explain any three built in function of the python with example. [6]
Answer: (any three function)
Below are some python built in fnctions
abs(): Returns the absolute value of a number
Return the absolute value of a number:
Example: x = abs(-7.25)
o/p : 7.25
Q3) a) Explain any two from the following string operations with example.
i. Concatenation
ii. Repetition
iii. Slicing
iv. Slice Range [6]
Answer:
i. Concatenation:
ii. Repetition: Sometimes we need to repeat the string in the program, and we can do
this easily by using the repetition operator in Python. The repetition operator is
denoted by a '*' symbol and is useful for repeating strings to a certain length.
o/p:
('a', 'b')
iv. Range Slice: This operation in python is used to slice or break the part of a list or
tuple or string. Create a tuple and a slice object. Start the slice object at position 3,
and slice to position 5, and return the result.
Exapmle: a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(3, 5)
print(a[x])
o/p: ('d', 'e')
b) Explain iteration to the string using for loop or any other way. [5]
Answer: The iteration to the string is also called as Looping Through a String.
Iteration is the function in python through which you can call every letter of the strings
one by one and perform individual tasks on them. Even strings are iterable objects, they
contain a sequence of characters.
Example: for x in "banana":
Print (x)
o/p: b
a
n
a
n
a
c) Write a python program to count the occurrences of each word in a
given sentence. [6]
Answer:
OR
Q4) a) Explain any three from the following string methods with example.
i) index() ii) islower() iii) Split vi) Join v) upper() [6]
Answer:
i) index(): Searches the string for a specified value and returns the position of where
it was found.
Example: txt = "Hello, welcome to my world."
x = txt.index("welcome")
print(x)
o/p: 7
ii) islower(): Returns True if all characters in the string are lower case
Example: txt = "hello world!"
x = txt.islower()
print(x)
o/p: True
iii) Split(): Splits the string at the specified separator, and returns a list
x = txt.split()
print(x)
o/p: True
x = "#".join(myTuple)
print(x)
o/p: John#Peter#Vicky
x = txt.upper()
print(x)
o/p: HELLO MY FRIENDS
Adding new data and functions is not easy. Adding new data and function is easy.
Procedural programming does not have any proper way Object-oriented programming provides data hiding so it
of hiding data so it is less secure. is more secure.
In procedural programming, there is no concept of data In object-oriented programming, the concept of data
hiding and inheritance. hiding and inheritance is used.
Procedural Oriented Programming Object-Oriented Programming
Procedural programming is used for designing Object-oriented programming is used for designing
medium-sized programs. large and complex programs.
Procedural programming uses the concept of procedure Object-oriented programming uses the concept of
abstraction. data abstraction.
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
Multilevel Inheritance:
In multilevel inheritance, features of the base class and the derived class are further
inherited into the new derived class. This is similar to a relationship representing a
child and grandfather.
Syntax:
Class A:
# Properties of class A
Class B(A):
# Class B inheriting property of class A
# more properties of class B
Class C(B):
# Class C inheriting property of class B
# thus, Class C also inherits properties of class A
# more properties of class C
Output:
class c3
class c2
class c1
Multiple Inheritance:
When a class can be derived from more than one base classes this type of
inheritance is called multiple inheritance. In multiple inheritance, all the features of
the base classes are inherited into the derived class.
Syntax:
Class A:
# variable of class A
# functions of class A
Class B:
# variable of class B
# functions of class B
Class C(A,B):
# Class C inheriting property of both class A and B
# more properties of class C
# Derived class
class Son(Father,Mother):
def display3(self):
print("Son")
s1 = Son()
s1.display3()
s1.display2()
s1.display1()
Output:
Son
Mother
Father
c) With the help of an example explain the significance of the init ( ) method. [5]
Answer: ( 3 marks for explanation, 2 marks for example with output)
Init or initialize Method (Creating constructor):
• Constructors are generally used for instantiating an object.
• The task of constructors is to initialize (assign values) to the data
members of the class when an object of class is created.
• In Python the __init__() method is called the constructor and is always
called when an object is created.
class student:
def __init__(self,rollno,name,age):
print("student object is created")
p1=student(11,"Ajay",20)
print("Roll No of student= ",p1.rollno)
print("Name No of student= ",p1.name)
print("Age No of student= ",p1.age)
Output:
student object is created
Roll No of student= 11
Name No of student= Ajay
Age No of student= 20
OR
Q6) a) Explain following Terms:
i) Encapsulation ii) Polymorphism [6]
Answer:
Encapsulation: (at least 3 correct point with definition)
1) It is the process of binding together the methods and data variables as a single entity i.e.
class. It hides the data within the class and makes it available only through the methods.
Or It is the process of wrapping up of data (properties) and behavior (methods) of an
object into a single unit and the unit is called a Class.
2) Encapsulation enables data hiding, hiding irrelevant information from users of a class and
exposing only the relevant details required by the user.
3) One can declare the methods or the attributes protected by using a single underscore ( _ )
before their names. Such as- self._name or def _method( ); Both of these lines tell that the
attribute and method are protected and should not be used outside the access of the class
and sub-classes but can be accessed by class methods and objects.
4) Though Python uses ‘ _ ‘ just as a coding convention, it tells that you should use these
attributes/methods within the scope of the class.
5) For actually preventing the access of attributes/methods from outside the scope of a class,
you can use “private members“. In order to declare the attributes/method as private
members, use double underscore ( __ ) in the prefix. Such as – self.__name or def
__method(); Both of these lines tell that the attribute and method are private and access is
not possible from outside the class.
obj_bird = Bird()
obj_parr = parrot()
obj_peng = penguin()
obj_bird.intro()
obj_bird.flight()
obj_parr.intro()
obj_parr.flight()
obj_peng.intro()
obj_peng.flight()
Output:
There are different types of birds
Most of the birds can fly but some cannot
There are different types of bird
Parrots can fly
There are many types of birds
Penguins do not fly
b) With the help of an example explain the significance of the init () method or
constructor. [5]
Answer:
(Mistakenly repeated question, refer Q5 (c) for answer)
c) Write a python program that uses class to store exam number and marks of four
subjects. Use list append to store the marks of four subjects. [7]
Answer:
Output:
Name: Mathews
Roll no: 3
Division: A
Enter the marks of respective subjects:
Engineering Physics: 50
Engineering Mathematics: 40
Basic Electrical Engineering: 70
Programming and Problem Solving: 80
name: Mathews
Roll no: 3
Division: A
Marks: ['50', '40', '70', '80']
Q7) a) Write a python program that reads data from one file and write into another file. [6]
Answer: (6 marks just to write correct program)
with open (‘ice and fire.txt’) as f:
with open (‘out.txt’, ‘w’) as f1:
for line in f:
f1.write(line)
b) Define files and enlist types of files with multiple examples. [6]
Answer: (2 marks for definition and 2 marks each for enlisting types)
File:
1. File is storage space for data or information. File is nothing but an object that preserves
data or information.
2. Every file is having a name “filename”.
3. For creating files you can use multiple softwares available in the computer. For example
you can use text editor to create text file.
4. Whenever file is saved, it has two aspects associated with it.
1. The file name
2. The extension of the file
5. In computer system file can be of two types
1. Text File
2. Binary File
Text File:
• The file which is in human readable form, where each line ends with EOL symbol(\n) by
default.
• We use various text files like program source code, setup scripts, technical
documentation, program generated output and logs, configuration files.
• Common extensions that are in text file formats as following
1. Webstandards: html, xml, css, svg, json…
2. Source code: c, cpp, h, cs, js, py, java, rb….
3. Documents: txt, tex, asciidoc,….
4. Tabular Data: csv, tsv….
• For opening text file we need text editor. We can use different editors for creating and
viewing text file i.e. we can create text file in one type of editor and open same file in
another one.
Binary File:
• In this type of files data is represented in the machine understandable format. Hence these
are difficult to understand ny viewing it. As software engineers use binary files in daily
life eg. Such software’s include MS Office, Abode Photoshop, and various audio viode
media players.
• Typically, computer users deals with binary files more than text files. Unlike text file, in
binary file there is no EOL symbol.
• Common extensions that are in Binary file formats as following
1. Images: jpg, png, gif, bmp, tiff,.…
2. Videos: mp4, mkv, avi, mov, mpg, vob….
3. Audio: mp3, aac, wav, flac, ogg, mka, wma….
4. Documents: pdf, doc, xls, ppt, docx, odt…..
5. Archive: zip, rar, 7z, tar, iso….
6. Databases: mdb, accde, frm, sqlite,….
7. Executable: exe, dll, so, class….
• Unlike text files, binary files need same software to read the file which is used to create
the file. Binary files need matching softwares for reading and writing.
c) Define dictionary with syntax. Enlist any four dictionary methods. [5]
Answer:
1. Dictionaries are defined in terms of key-value pairs. Usually keys are defined in terms of
strings/numbers. But value can be of any type.
2. Dictionaries are closed in curly braces and are mutable data type.
3. At time of accessing key, if key is not present it will generate “Keyerror”.
Any Four Dictionary Methods:
a. Clear (): Removes all the elements from the dictionary.
b. copy () Returns a copy of the dictionary
c. items () Returns a list containing a tuple for each key value pair
d. keys () Returns a list containing the dictionary's keys
e. pop() Removes the element with the specified key
OR
Q8) a) Explain the method to open a text file as well as write down the file modes in which
files can be opened. [6]
Answer:
For opening a file, python is provided with a built in function called as “open()”.
Function Description
mode
r Open file in read mode if file not present then it will raise the error
w Open file in write mode, if file does not present it will create a file and
open it in write mode.
a Append new contents at the end of existing file. If file is not present it will
create a file and open it in append mode.
t Text mode, it is default mode in which file opens.
b Open a file binary mode.
b) Why do we need files? Explain relative and absolute path in files. [6]
Answer:
File is a storage space for data or information. In other words file is an object that
preserves data or information. We need files for storage purpose. Every file has a name
associated with it called filename. Using this filename we can access or update data or
information as and when needed. Absolute file paths are notated by a leading forward
slash or drive label. For example, /home/example_user/example_directory or
C:/system32/cmd.exe.
Absolute Path in files:
An absolute file path describes how to access a given file or directory, starting
from the root of the file system. A file path is also called a pathname. Relative file paths
are notated by a lack of a leading forward slash. For example, example_directory.
Relative path in files:
A relative file path is interpreted from the perspective your current working
directory. If you use a relative file path from the wrong directory, then the path will refer
to a different file than you intend, or it will refer to no file at all. When you run a python
program, its current working directory is initialized to whatever your current directory
was when you ran the program. It can be retrieved using the function os.getcwd().
c) Write a python program to add a key to a dictionary. [5]
Answer:
dict2={'name': 'Bob', 'Age': 21, 'Marks':88.0}
dict2['City']='London'
print('Modified contents of dictionary are:\n',dict2)
Output:
The contents of dictionary are: {'name': 'Bob', 'Age': 21, 'Marks': 88.0)
Modified contents of dictionary are: {'name': 'Bob', 'Age': 21, 'Marks': 88.0, 'City':
'London'}