0% found this document useful (0 votes)
508 views21 pages

PPS Paper Solution

The document discusses programming and problem solving concepts in Python including functions, modules, and string operations. It provides examples of functions with parameters and return values, built-in modules like math and random, and string operations like concatenation, slicing, and iteration. Programming concepts like functions, modules, and string manipulation are explained with clear code examples.
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)
508 views21 pages

PPS Paper Solution

The document discusses programming and problem solving concepts in Python including functions, modules, and string operations. It provides examples of functions with parameters and return values, built-in modules like math and random, and string operations like concatenation, slicing, and iteration. Programming concepts like functions, modules, and string manipulation are explained with clear code examples.
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
You are on page 1/ 21

Programming and Problem Solving

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 random as ra:


ra.randint(0,9)

o/p: 5 __________(1 Mark)


iii. Matplotlib and pyplot:
a. It is a library used for creation of graphs.
b. Generally this can create 2 graphs and plots by using python
c. Matplotlib has a module named pyplot. It is used for plotting by providing
number of features like control line styles, fonts, naming axes etc. It provides
support for very wide variety of graphs like histogram, bar charts, error charts
etc.
iv. Numpy:
a. NumPy is a Python library used for working with arrays.It also has functions
for working in domain of linear algebra, fourier transform, and matrices.
b. NumPy was created in 2005 by Travis Oliphant. It is an open source project and
you can use it freely. NumPy stands for Numerical Python.
c. In Python we have lists that serve the purpose of arrays, but they are slow to
process.
d. NumPy aims to provide an array object that is up to 50x faster than traditional
Python lists.
e. The array object in NumPy is called ndarray, it provides a lot of supporting
functions that make working with ndarray very easy.
f. Arrays are very frequently used in data science, where speed and resources are
very important.
v. Date and Time Module:
A date in Python is not a data type of its own, but we can import a module named
datetime to work with dates as date objects.
Example:
Import the datetime module and display the current date:

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)

o/p: Enter a number to make its square: 4


The square of number is: 16
OR
Q2) a) Explain keyword arguments in python. Write a python program to demonstrate
keyword arguments. [6]
Answer:
Keyword Arguments: (2 Mark – explanation, 3 Mark – example, 1 Mark –example explain)
With keyword argument it is possible to use the name of the parameter while calling to
the function. This way the order of the arguments does not matter. The phrase Keyword
Arguments are often shortened to kwargs in Python documentations.
Example:
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

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

all(): Returns True if all items in an iterable object are true


Check if all items in a list are True:

Example: mylist = [True, True, True]


x = all(mylist)
o/p : True

any():Returns True if any item in an iterable object is true


Check if any of the items in a list are True:

Example: mylist = [False, True, False]


x = any(mylist)
o/p : True

ascii(): Returns a readable version of an object. Replaces none-ascii characters with


escape character
Escape non-ascii characters:

Example: x = ascii("My name is Ståle")


o/p: My name is St\e5le

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:

String concatenation means add strings together.

Use the + character to add a variable to another variable.

Example: x = "Python is "


y = "awesome"
z = x + y
print(z)

o/p: Python is awesome

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.

Example: str = 'Python program'


print(str*3)

o/p: Python programPython programPython program


iii. Slicing:
This operation in python is used to slice or break the part of a list or tuple or string.
It Creates a tuple and a slice object. Use the slice object to get only the two first
items of the tuple.
Example: a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(2)
print(a[x])

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

Example: txt = "welcome to the jungle"

x = txt.split()

print(x)
o/p: True

iv) Join() : Converts the elements of an iterable into a string


Example: myTuple = ("John", "Peter", "Vicky")

x = "#".join(myTuple)

print(x)
o/p: John#Peter#Vicky

v) upper(): Converts a string into upper case


Example: txt = "Hello my friends"

x = txt.upper()

print(x)
o/p: HELLO MY FRIENDS

b) What will be the output of following statement S = “Welcome to Python”.


i) Print (s[1:9])
ii) Print (s[ :6])
iii) Print (s[4: ])
iv) Print (s[1: –1])
v) Print (“Come” not in S) [5]
Answer:
i) elcome t
ii) Welcom
iii) ome to Python
iv) elcome to Pytho
v) True
c) Write short note on String module. Also explain ord() and chr() functions. [6]
Answer:
String Module: Python String module contains some constants, utility function, and
classes for string manipulation. It’s a built-in module and we have to import it before
using any of its constants and classes. Following are some string constatnts, we need to
import string module as given in example below.
import string
# string module constants
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print(string.digits)
print(string.hexdigits)
print(string.whitespace) # ' \t\n\r\x0b\x0c'
print(string.punctuation)
O/p:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
0123456789abcdefABCDEF
_______________________________
!"#$%&'()*+,-./:;?@[\]^_`{|}~
Q5) a) Explain difference in procedure oriented and object-oriented programming paradigms. [6]
Answer: (Any 6 correct differences)
Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the program is divided In object-oriented programming, the program is


into small parts called functions. divided into small parts called objects.

Procedural programming follows a top-down Object-oriented programming follows a bottom-up


approach. approach.

There is no access specifier in procedural Object-oriented programming has access specifiers


programming. like private, public, protected, etc.

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, overloading is not Overloading is possible in object-oriented


possible. programming.

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

In procedural programming, the function is more In object-oriented programming, data is more


important than the data. important than function.

Object-oriented programming is based on the real


Procedural programming is based on the unreal world. world.

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.

Code reusability present in object-oriented


Code reusability absent in procedural programming, programming.

Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.

b) Explain inheritance and all of its types with example. [7]


Answer:
Inheritance:
The mechanism of designing and constructing classes from other classes
is called inheritance.
Inheritance is the capability of one class to derive or inherit the properties from
some another class.
The new class is called derived class or child class and the class from which
this derived class has been inherited is the base class or parent class. The benefits
of inheritance are:
1. It represents real-world relationships well.
2. It provides reusability of a code. We don’t have to write the same code
again and again. Also, it allows us to add more features to a class without modifying it.
3. It is transitive in nature, which means that if class B inherits from another
class A, then all the subclasses of B would automatically inherit from class A.
Syntax:
Class A:
# Properties of class A
Class B(A):
# Class B inheriting property of class A
# more properties of class B

Example: Example of Inheritance without using constructor


class vehicle: #parent class
name="Maruti"
def display(self):
print("Name= ",self.name)
class category(vehicle): # drived class
price=400000
def disp_price(self):
print("price= ",self.price)
car1=category()
car1.display()
car1.disp_price()

o/p: Name= Maruti


price= 400000

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

Example: Python program to demonstrate multilevel inheritance


#Mutilevel Inheritance
class c1:
def display1(self):
print("class c1")
class c2(c1):
def display2(self):
print("class c2")
class c3(c2):
def display3(self):
print("class c3")
s1=c3()
s1.display3()
s1.display2()
s1.display1()

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

Example: Python program to demonstrate multiple inheritance


# Base class1
class Father:
def display1(self):
print("Father")
# Base class2
class Mother:
def display2(self):
print("Mother")

# 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.

Syntax of constructor declaration :


def __init__(self):
# body of the constructor

Example: For creating constructor use__init__ method called as constructor.

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.

ii) Polymorphism: (at least 3 correct point with definition)


1) This is a Greek word. If we break the term Polymorphism, we get “poly”-many and
“morph”-forms. So Polymorphism means having many forms. In OOP it refers to the
functions having the same names but carrying different functionalities.
2) It allows one interface to be used for a set of actions. It means same function name(but
different signatures) being used for different types.
3) When the function is called using the object audi then the function of class Audi is
called and when it is called using the object bmw then the function of class BMW is
called.
4) Its simple example can be taken as, a who is working as an employee in office, but at
home he has the roles of a father, a son, a brother etc.
Example:
class Bird:
def intro(self):
print("There are different types of birds")
def flight(self):
print("Most of the birds can fly but some cannot")
class parrot(Bird):
def flight(self):
print("Parrots can fly")
class penguin(Bird):
def flight(self):
print("Penguins do not fly")

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}

print ('The contents of dictionary are:', dict2)

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'}

You might also like