Pps Micro

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

https://t.me/sppu_fe_solve_paper Join our Telegram. Write a program to count the number of characters and words in the given string.

te a program to count the number of characters and words in the given string. Lambda function :
2) s = “Welcome to the world of python programming”  Python Lambda Functions are anonymous function means that the function is without a name. As
1) Define function with syntax. Elaborate your answer with an example
(Do not use built-function for the above example) we already know that the def keyword is used to define a normal function in Python. Similarly, the
Definition of Function :
lambda keyword is used to define an anonymous function in Python.
 A function is a block of organized and reusable program code that perform single, specific, and
 Notice that the anonymous function does not have a return keyword. This is because the anonymous
well defined task. Python enables its programmer to break up a program into functions, each of
function will automatically return the result of the expression in the function once it is executed.
which can be written more or less independent of each other. Therefore, the code of one function is
Syntax :
completely insulated from the codes of the other function.
lambda argument(s) : expression
 A function f that uses another function g is known as the calling function and g is known as the
called function.
Example :
Call to a function :
Program that uses Lambda function to multiply two numbers :
 A function can be called from any place in python script.
 Place or line of call of function should be after place or line of declaration of function.
Ans:

Syntax :
def <space> <function_name> (<parameters>):
……
…….
return <variables to be returned>

Ans:
Example :

Ans:

3) Write a program to find the factorial of a given number.

Ans:

5) Write a Python program to find area of Triangle using function

4) What is Lambda function? Write a program that uses Lambda function to multiply two numbers.

Ans: Ans:

7) Write a Python program to find area of circle using function


Write a short notes on : (Explain with one example)
9) a) Variable length argument b) Default argument

Ans:
Variable length argument :
• Variable length argument is an argument that can accept any number of values.
• Variable length arguments written with * symbol.
• It stores all values in tuple.
Syntax:
Def function_name ([arg1, arg2,….] * var_args_tuple):
function statement
return expression
Ans: Example:

6) Write a Python program to find area of Rectangle using function 8) Write a Python program to find circumference of circle using function

Python ord( ): i) lstrip and rstrip :-


Default argument : Python ord( ) function takes string argument of a single Unicode character and return its integer Unicode lstrip()- remove all leading whitespace in string.
• One of the arguments to a function may have its default value. code point value. Let‟s look at some examples of using ord() function. Syntax- string.lstrip(characters)
Example- 1
• For example laptop has default built in speakers. So if no speaker is connected it will play default Examples:
s=" Hello"
speaker. print(s.lstrip())
• Similarly in function argument, a default value can be assigned to an argument. output- Hello
Example 2-
• Now if value for this argument is not passed by the user then function will consider that arguments s="*****Hello"
default value. print(s.lstrip("*"))
• Calling functions with very large number of arguments can be made easy by default values
output- Hello

Example : In the following example, we are not passing the value of age and using its default value. rstrip()- remove all trailing whitespace in string.
Syntax- string.lstrip(characters)
Example 1-
s="Hello "
print(s.rstrip())
output-Hello
Example 2-
s="Hello*****"
print(s.rstrip("*"))
output- Hello

Ans: ii) split


split() : It takes one argument. The string is then split around every occurrence of the argument in the string.
Ans: Python chr( ) :
Ans: Python chr( ) function takes integer argument and return the string representing a character at that code Example 1- In the below example we are splitting the string around every occurrence of :

point.
s="Welcome:to:Python"
Examples:
print(s.split(":"))
output-
['Welcome', 'to', 'Python']

iii) zfill : It return the string with zeros left padded to the total width of string

Example 1- In the below example, total width of string is 6 and we are using zfill( ) method by
passing 15 as an argument value, so it returns the string with 9 zeros padded to input string.
s="Python"
print(s.zfill(15))
output-
000000000Python

Explain the following string operations with suitable example.


12)
i) Concatenation ii) Appending iii) String repetition

Explain following string methods with example.


11)
i) 1 strip & r strip ii) Split iii) Zfill
10) Differentiate between ord( ) and chr( ) function. (Explain with example)
What will be the output of following statement S = “Welcome to Python”. Files are very important part of a computer system.
String Concatenation: i) print (s[1:9]) • Data on non volatile storage media is stored in named locations on the media called files.
• The word concatenates means to join together.
ii) print (s[ :6]) • A file is a collection of data stored on a secondary storage device like hard disks, pen-drives, DVD
• Concatenation is the operation of joining two strings together. 13)
• Python Strings can join using the concatenation operator +. iii) print (s[4: ]) or CDs.
iv) print (s[1: –1]) • Files are loaded in main memory or RAM when required.
str="Python"
str1="Programming" v) Count the number of characters in the given string • All programs need the input to process and output to display data. And everything needs a file as
str2="!!"
name storage compartments on computers that are managed by OS.
print(str)
print(str1) • Though variables provide us a way to store data while the program runs, if we want out data to
print(str2)
persist even after the termination of the program, we have to save it to a file.
str3=str+" "+str1+".."+str2
print(str3)
File Path (pathname)
String appending:
• Append means to add something at the end. In python you can add one string at the end of another • Location where file is saved or stored.
string using the += operator.
• Each file has a path which helps system to identify the file.
• "Concatenate" joins two specific items together, whereas "append" adds another string to existing
string. • Most file systems that are used today stores files in a tree (or hierarchical) structure.
Ex- s="Py"
• 2 types of file path
s=s+"thon"
EX:-str="hello:" 1. Absolute path
name=input("Enter name")
2. Relative path
str+=name
print(str)
Ans:
Multiplication or Repetition : Ans:
• To write the same text multiple times, multiplication or repetition is used.
• Multiplication can be done using operator *.
str= "My Class is Best..."
print(str*3)
Output :
My Class is Best… Ans:
My Class is Best…
My Class is Best… 1. Absolute path- always contain root and complete directory.
Ex- C:\Students\Under Graduate\Btech_cs.docx
2. Relative path- describe path from current working directory.
Ex- If current working directory is C:\Students then relative path is Under Graduate\Btech_CS.docx

Differentiate between Monolithic and Procedural programming


15)
(Note : For answer of this question, also draw the diagrams from Question N0. 17)
14) Why do we need files? Explain relative and absolute path in files.

Sr. No. Monolithic Programming paradigm Procedural programming Paradigm Formatting with % Operator. Definition of programming paradigm-
1 Single Block of code. Code break into subroutines.  % sign, this string formatting operator is one of the exciting feature in Python. A programming paradigm is a fundamental style of programming that defines how the structure
2 Duplication of code. Duplication of code is avoided.  The format operator, % allows user to construct strings, replacing parts of strings with the and basic elements of a computer program will be built.
data stored in variables.
3 Lengthy code. Small code as compares to monolithic  The syntax for the string formatting operator is. List of programming paradigm-
programming. "<Format>" %(<Values>) 1) Monolithic programming paradigm
4 Performance is slow. Performance is fast as compare to Example - 2) Procedural programming paradigm
Ans: monolithic programming paradigm. 3) Structured programmingparadigm
name= "ABC"
5 Size of program is large. Small size program. 4) Object Oriented Programming paradigm
age= 8
6 Data declare globally. Here also data is declared globally. 1. Monolithic programming-
print("Name=%s and Age=%d"%(name, age))
7 No security to data. Here also data is not secure. -Monolithic means formed of single block.
print("Name=%s and Age=%d"%('xyz', 10))
8 Ex-BASIC (Beginner's All-purpose Ex- FORTRAN (FORmula -Here complete program is written as a sequence.
Symbolic Instruction Code), Assembly TRANslation), COBOL (Common -There are no modules or functions used.
language. Business-Oriented Language). -Ex- BASIC (Beginner's All-purpose Symbolic Instruction Code), Assembly language.

Ans: Ans:

Fig- Structure of monolithic program.


• Advantage:
• It is good for small size program.
• Disadvantage
• Its problem is there can be lot of repetition of code when same operation has to bedone
many times.
• No security to data.
• Lengthy code.
2. Procedural programming-
• Here program is divided in procedures or module or functions.
• Function is a small unit of programming logic.
• Ex- FORTRAN (FORmula TRANslation), COBOL (Common Business-Oriented
Language)

16) Explain string formatting operators in details. (Any three)

17) Define programming paradigm. List programming paradigms. Explain any three.

• Advantages Python Membership Operators :


• No duplication of code. Python offers two membership operators to check or validate the membership of a value. It tests for
membership in a sequence, such as strings, lists, or tuples.
• We can pass data to other function and take dada from other function.
in operator:
• It is readable program.
The „in‟ operator is used to check if a character/ substring/ element exists in a sequence or not. Evaluate to
• It is easy to find errors or especially logical errors. True if it finds the specified element in a sequence otherwise False.

• Disadvantage Example :
• Data can be modified by any procedure or part of the program. i.e No security for data.
• Main focus on function, secondary focus on the data. i.e function is created for data. Data
Fig: Procedure program is not created for function.
4. Object Oriented Programming (OOP) Paradigm- # returns True because a sequence with the value "banana" is in the list
Advantages: • Here data is major focus. (Function acts on data)
• Duplication of code is avoided (reduces redundancy). • Data and functions are put together to avoid misuse or un-intentional modifications in data.
• Same function can be used multiple times in one program whenever the operation is • Here “Class” puts together data and functions.
needed. • Only functions belonging to that class can modify the data.
• ‘not in’ operator :
It makes program readable. • follow bottom-up approach for problem solving.
Evaluates to true if it does not finds a variable in the specified sequence and false otherwise.
Disadvantages • Also, OOP supports features like inheritance, abstraction, etc.
Example
• No security to data • Ex- C++, Java, Python
• Data can be modified by any procedure. Ans:
• Data is not protected properly.
• It may include „goto‟ like statements which makes program un-structured and poor in
readability.
3. Structured programmingParadigm-
Fig- Object
-This is improved/ advanced version of procedural language. It contains top downmodular
Advantages
approach, control structure, function oriented programming.
• OOP features enable re-use of programs very easy.
-Here program is written in a structured format compulsorily.
• Data is protected here.
-Now most of the procedural programming languages support structured programming
Disadvantage
paradigm.
• Dependence of a class on other class may lead to inefficient programs.
-Ex- C and Pascal

Fig: Structured program


Write a python program to create class student to store exam number and marks of four subjects. Use list to
19)
store the marks of four subjects.

18) Explain Membership Operators in Python with example (In and not In operator)
Documentation String: Class:
• In python, programmer can write a documentation for every function.  Class is Plan/ Model/ Blueprint/ Design of an object.
• This documentation can be accessed by other functions.
Advantage of Document string • class provides a template or a blueprint that describes the structure and behavior of a set of
• It is useful when we want to know about any function in python. similar objects.
• Programmer can simply print the document string of that function and can know what that
function does. • class can have a data and functions.
• A class creates a new type and object is an instance (or variable) of the class.
Documentation String Example:
def f1(): • In python everything is object or an instance of any class.
"""This is f1 function. • Syntax for defining class
This function print Hello world on console"""
print("Hello world!!!") class class_name:
print(f1. doc )
statement 1
f1()
statement 2
statement N
Object:
• objects- Instance of any class is called object. Or
Actual implementation of class is called object
• Creating object:
• Once class is define next task is to create an object (or instance) of that class.

Ans: • For a class we can create any number of objects.


Ans: Ans:
• The object can then access class variables and class methods using the dot operator(.).
• Syntax for creating object-
object_name = class_name()
• Creating an object or instance of class is known as class instantiation.
• Syntax for accessing class member through the class object-
object_name.class_member_name
• Syntax for defining class
class class_name:
statement 1
statement 2
statement N

20) Explain with example Docstring (Documentation String)


21) Explain the concept of a class and an object in OOP. Write syntax for creating class. 22) Explain Public and Private Data Members in a class with an example..

Public data member- Files are very important part of a computer system. • getcwd()- To know current working directory.
• Public variables are those variables that are defined in the class and can be accessed from Ex: import os
 A file is a collection of data stored on a secondary storage device like hard disks, pen- cwd= os.getcwd()
anywhere in the program.
drives, DVD or CDs.
print("Current working directory", cwd)
• Public variables can be accessed from within the class as well as from outside the class in  Files are loaded in main memory or RAM when required.
which it is defined.  Data on nonvolatile storage media is stored in named locations on the media called
files. • chdir()- change current directory. Method take name of directory whichyou want to make the current
Private Data Member-
directory.
• Private variables are those variables that are defined in the class with a double underscore Following file Access modes are used for opening files. Ex- import os
prefix( ). 1) "r" : read
os.chdir("FE")
• These variables can be accessed only from within the class and not from outside the class.  It is a read mode. Here file is opened for reading ONLY.
cwd=os.getcwd()
 Here file reference points to start of the file.
Example -1 print(cwd)
 If the specified file does not exist then we will get FileNotFoundError.
2) "w" : write
 Open an existing file for write operation. • mkdir()- To create a new directory(create subdirectory in currentworking directory)
 If the file already contains some data then it will be overridden. Ex- import os
 If the specified file is not already available then this mode will create that file.
os.mkdir("FE\PPS Program")
3) "a" : append
print("Created")
 Open an existing file for append operation.
 It won‟t override existing data.
 If the specified file is not available then this mode will create a new file • makedirs()- To create both parent and child directory
4) "r+": Ex: import os
Ans:  This mode allows reading and writing. Here also reference is placed at start of the file. Ans: os.makedirs("FE\PPS\Practicals")
Ans:
Previous data in file will not be deleted.
5) "w+":
 This mode allows both writing and reading. • rmdir() - To remove directory. (remove empty directory)
 It will override existing data. Ex- import os
6) "a+": os.rmdir("FE/PPS/Practicals")
Output-  Here appending and reading both are allowed.
 Don‟t override existing data.
• removedirs()- All directory remove.
 File reference is always at end of the file.
7) "x": Exclusive Ex- import os
 To open file in exclusive creation mode for write operation. os.removedirs("FE\PPS\Practicals")
If file already exist then we will get FileExistError. • rename()
Ex- import os
os.rename("FE","First Year")

• listdir()- To know content of directory.


Ex- import os
l=os.listdir("FE")
print(l)

What is a file? Explain different access modes for opening files.


23)
Read Write, Append 25) Explain any three methods for reading and writing files.

24) Explain different directory methods with suitable examples.

Dictionaries are used to store data values in key : value pairs. A dictionary is a collection which
Following are some methods for reading files. is ordered*, changeable and do not allow duplicates. If we trying to insert an entry with
1. f.read()-> To read total data
duplicate key then old value will be replaced with new value
2. f.read(n)-> To read n character from file
3. f.readline()--> To read only one line
4. f.readlines()--> to read all lines into a list
Creating Dictionary:
i={}

1. f.read()-> d={1:"One",2:"Two",4:"Four"}

f=open("Sample.txt") Accessing element- Programming and Problem Solving


a=f.read() di={1:"One",2:"Two",3:"Three"}

print(a) • print(di.keys())
o/p: dict_keys([1, 2, 3])

2. f.read(n)-> Ans: • print( di.values())

f=open("Sample.txt") o/p: dict_values(['One', 'Two', 'Three'])

a=f.read(7) • print(di.get(1))

print(a) o/p: 'One‟


• print(di[2]) Q1) a) What is function? Write its two advantages. Explain with example Docstring. [6]
3. f.readline()--> o/p: 'Two‟
Function:
f=open("Sample.txt") • Inserting/Modifying element-

line1=f.readline() • di[4]="Four" Functions are group of statements that are bundled together to perform a specific
di= {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four‟} task. Functions provide an incredibly unique aspect of programming called as modularity.
Ans: print(line1)
line2=f.readline() • Updating (1 Mark)
print(line2) • di[3]="Threeeee"
Advantages: (Each advantage 1 Mark / max 2 advantages)
line3=f.readline() di={1: 'One', 2: 'Two', 3: 'Threeeee', 4: 'Four'}
1. To provide the readability of the code
print(line3)
2. Provides the facility of the reusability of the code, same function can be used in any
4. f.readlines()--> program rather than writing the same code from scratch.
f=open("Sample.txt") 3. Reduces the size of the code, duplicate set of statements are replaced by function calls.
lines=f.readlines()
Docstring: (1 Mark for definition, 2 Marks for code or example)
for l in lines:
print(l) 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)

26) What is a dictionary? How to create, access and modify dictionary elements
b) Explain any two standard libraries/modules from following support for very wide variety of graphs like histogram, bar charts, error charts Q2) a) Explain keyword arguments in python. Write a python program to demonstrate
etc. keyword arguments. [6]
i. Math Module
iv. Numpy:
ii. Random Module Answer:
a. NumPy is a Python library used for working with arrays.It also has functions
iii. Matplotlib and pyplot
for working in domain of linear algebra, fourier transform, and matrices. Keyword Arguments: (2 Mark – explanation, 3 Mark – example, 1 Mark –example explain)
iv. Numpy
b. NumPy was created in 2005 by Travis Oliphant. It is an open source project and With keyword argument it is possible to use the name of the parameter while calling to
v. Date and time module [6]
you can use it freely. NumPy stands for Numerical Python. the function. This way the order of the arguments does not matter. The phrase Keyword
(1 Marks each for correct points) c. In Python we have lists that serve the purpose of arrays, but they are slow to Arguments are often shortened to kwargs in Python documentations.
process.
i. Math Module:
d. NumPy aims to provide an array object that is up to 50x faster than traditional Example:
Math module is python library which supports various mathematical operations def my_function(child3, child2, child1):
such as ceil, floor etc. (1 Mark) Python lists.
print("The youngest child is " + child3)
a. Ceil operation using math module: This operation returns the ceiling or the e. The array object in NumPy is called ndarray, it provides a lot of supporting
upper value of x as integer. functions that make working with ndarray very easy. my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
f. Arrays are very frequently used in data science, where speed and resources are
very important. As from above you can see that at the time of calling the function arguments we have
import math as mp
v. Date and Time Module: called them by using their names. Such as child1 = “Emil”.
mp.ceil (1.5) (1 Mark)
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.
o/p: 2 b) Write python program using function to find whether number is odd or even. [6]
Example:
Import the datetime module and display the current date: Answer:
b. Floor Operation using math module: This operation returns the floor or the
a = int (input(“ Enter a number to check is it even or odd? : “))
lower value of x as integer. import datetime def even_odd ():
x = datetime.datetime.now()
print(x) if a%2 == 0:
import math as mp
print(“ Number is Even”)
mp.floor (1.5) Ouput:
else:
(1 Mark) 2022-07-23 20:38:13.350780
print(“ Number is Odd”)
o/p: 1
o/p: Enter a number to check is it even or odd? : 5
ii. Random Module:
c) Write a python program using function which accepts a number as argument and Number is Odd
a. This module is pseudo random number generator. (1 Mark)
returns square of it. [6]
b. The randint function is used to return any random integer between the given
range such as given below example. (1 Mark) Answer: (6 Marks for correct program with o/p) c) Explain any three built in function of the python with example. [6]
a = int (input(“ Enter a number to make its square: “)) Answer: (any three function)
Import random as ra:
ra.randint(0,9) def square (a): Below are some python built in fnctions
print (“The square of number is: ”, a) abs(): Returns the absolute value of a number
o/p: 5 (1 Mark)
iii. Matplotlib and pyplot: Return the absolute value of a number:
a. It is a library used for creation of graphs. o/p: Enter a number to make its square: 4 Example: x = abs(-7.25)
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 The square of number is: 16 o/p : 7.25
number of features like control line styles, fonts, naming axes etc. It provides OR all(): Returns True if all items in an iterable object are true

Check if all items in a list are True: print(str*3) Answer:


Example: mylist = [True, True, True] o/p: Python programPython programPython program
x = all(mylist) iii. Slicing:
o/p : True This operation in python is used to slice or break the part of a list or tuple or string.
any():Returns True if any item in an iterable object is true It Creates a tuple and a slice object. Use the slice object to get only the two first
items of the tuple.
Check if any of the items in a list are True: Example: a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(2)
Example: mylist = [False, True, False] print(a[x])
x = any(mylist)
o/p : True o/p:
('a', 'b')
ascii(): Returns a readable version of an object. Replaces none-ascii characters with
escape character 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,
Escape non-ascii characters: and slice to position 5, and return the result.
Example: x = ascii("My name is Ståle") Exapmle: a = ("a", "b", "c", "d", "e", "f", "g", "h") OR
o/p: My name is St\e5le x = slice(3, 5) Q4) a) Explain any three from the following string methods with example.
Q3) a) Explain any two from the following string operations with example. print(a[x])
i) index() ii) islower() iii) Split vi) Join v) upper() [6]
i. Concatenation o/p: ('d', 'e')
Answer:
ii. Repetition b) Explain iteration to the string using for loop or any other way. [5]
iii. Slicing i) index(): Searches the string for a specified value and returns the position of where
Answer: The iteration to the string is also called as Looping Through a String.
iv. Slice Range [6] it was found.
Iteration is the function in python through which you can call every letter of the strings Example: txt = "Hello, welcome to my world."
Answer: one by one and perform individual tasks on them. Even strings are iterable objects, they x = txt.index("welcome")
i. Concatenation: contain a sequence of characters. print(x)
Example: for x in "banana":
String concatenation means add strings together. o/p: 7
Print (x) ii) islower(): Returns True if all characters in the string are lower case
Use the + character to add a variable to another variable. o/p: b Example: txt = "hello world!"
a
Example: x = "Python is "
n x = txt.islower()
y = "awesome"
a
z = x + y
print(z) n print(x)
a
c) Write a python program to count the occurrences of each word in a o/p: True
o/p: Python is awesome
iii) Split(): Splits the string at the specified separator, and returns a list
ii. Repetition: Sometimes we need to repeat the string in the program, and we can do given sentence. [6]
this easily by using the repetition operator in Python. The repetition operator is Example: txt = "welcome to the jungle"
denoted by a '*' symbol and is useful for repeating strings to a certain length.
x = txt.split()
Example: str = 'Python program'
print(x)

o/p: True print(string.ascii_letters) Procedural Oriented Programming Object-Oriented Programming


iv) Join() : Converts the elements of an iterable into a string print(string.ascii_lowercase)
print(string.ascii_uppercase)
Example: myTuple = ("John", "Peter", "Vicky") print(string.digits) In procedural programming, the function is more In object-oriented programming, data is more
important than the data. important than function.
print(string.hexdigits)
x = "#".join(myTuple)
print(string.whitespace) # ' \t\n\r\x0b\x0c'
Object-oriented programming is based on the real
print(x) print(string.punctuation) Procedural programming is based on the unreal world. world.
o/p: John#Peter#Vicky O/p:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
v) upper(): Converts a string into upper case
abcdefghijklmnopqrstuvwxyz Procedural programming is used for designing Object-oriented programming is used for designing
Example: txt = "Hello my friends" medium-sized programs. large and complex programs.
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
x = txt.upper() Procedural programming uses the concept of procedure Object-oriented programming uses the concept of
0123456789abcdefABCDEF
abstraction. data abstraction.
print(x)
!"#$%&'()*+,-./:;?@[\]^_`{|}~
o/p: HELLO MY FRIENDS Code reusability present in object-oriented
Q5) a) Explain difference in procedure oriented and object-oriented programming paradigms. [6] Code reusability absent in procedural programming, programming.
b) What will be the output of following statement S = “Welcome to Python”.
Answer: (Any 6 correct differences)
i) Print (s[1:9]) Procedural Oriented Programming Object-Oriented Programming
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.

ii) Print (s[ :6])


iii) Print (s[4: ]) 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. b) Explain inheritance and all of its types with example. [7]
iv) Print (s[1: –1]) Answer:
v) Print (“Come” not in S) [5] Procedural programming follows a top-down Object-oriented programming follows a bottom-up
Inheritance:
approach. approach.
Answer: The mechanism of designing and constructing classes from other classes
There is no access specifier in procedural Object-oriented programming has access specifiers is called inheritance.
i) elcome t
programming. like private, public, protected, etc.
ii) Welcom Inheritance is the capability of one class to derive or inherit the properties from
iii) ome to Python some another class.
Adding new data and functions is not easy. Adding new data and function is easy. The new class is called derived class or child class and the class from which
iv) elcome to Pytho
v) True this derived class has been inherited is the base class or parent class. The benefits
Procedural programming does not have any proper way Object-oriented programming provides data hiding so it of inheritance are:
c) Write short note on String module. Also explain ord() and chr() functions. [6] of hiding data so it is less secure. is more secure.
1. It represents real-world relationships well.
Answer: 2. It provides reusability of a code. We don’t have to write the same code
In procedural programming, overloading is not Overloading is possible in object-oriented
again and again. Also, it allows us to add more features to a class without modifying it.
String Module: Python String module contains some constants, utility function, and possible. programming.
3. It is transitive in nature, which means that if class B inherits from another
classes for string manipulation. It’s a built-in module and we have to import it before
class A, then all the subclasses of B would automatically inherit from class A.
using any of its constants and classes. Following are some string constatnts, we need to In procedural programming, there is no concept of data In object-oriented programming, the concept of data
import string module as given in example below. hiding and inheritance. hiding and inheritance is used.

import string
# string module constants
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: Syntax:
Class A: Class A:
# Properties of class A # Properties of class A
Class B(A): Class B(A):
# Class B inheriting property of class A # Class B inheriting property of class A
# more properties of class B # more properties of class B
Class C(B):
Example: Example of Inheritance without using constructor # Class C inheriting property of class B
class vehicle: #parent class Syntax:
# thus, Class C also inherits properties of class A
name="Maruti" Class A:
# more properties of class C
def display(self): # variable of class A
print("Name= ",self.name) # functions of class A
Example: Python program to demonstrate multilevel inheritance
class category(vehicle): # drived class Class B:
#Mutilevel Inheritance
price=400000 # variable of class B
class c1:
def disp_price(self): # functions of class B
def display1(self):
print("price= ",self.price) Class C(A,B):
print("class c1")
car1=category() # Class C inheriting property of both class A and B
class c2(c1):
car1.display() # more properties of class C
def display2(self):
car1.disp_price() print("class c2")
class c3(c2):
o/p: Name= Maruti Example: Python program to demonstrate multiple inheritance
def display3(self):
price= 400000 # Base class1
print("class c3")
class Father:
s1=c3()
Multilevel Inheritance: def display1(self):
s1.display3()
In multilevel inheritance, features of the base class and the derived class are further print("Father")
s1.display2()
inherited into the new derived class. This is similar to a relationship representing a # Base class2
s1.display1()
child and grandfather. class Mother:
def display2(self):
Output:
print("Mother")
class c3
class c2
class c1
# Derived class
class Son(Father,Mother):

def display3(self): Name No of student= Ajay class Bird:


print("Son") Age No of student= 20 def intro(self):
print("There are different types of birds")
s1 = Son() OR
def flight(self):
s1.display3()
Q6) a) Explain following Terms: print("Most of the birds can fly but some cannot")
s1.display2() class parrot(Bird):
s1.display1() i) Encapsulation ii) Polymorphism [6] def flight(self):
print("Parrots can fly")
Answer: class penguin(Bird):
Output:
Encapsulation: (at least 3 correct point with definition) def flight(self):
Son
print("Penguins do not fly")
Mother 1) It is the process of binding together the methods and data variables as a single entity i.e.
Father class. It hides the data within the class and makes it available only through the methods. obj_bird = Bird()
Or It is the process of wrapping up of data (properties) and behavior (methods) of an obj_parr = parrot()
c) With the help of an example explain the significance of the init ( ) method. [5] obj_peng = penguin()
object into a single unit and the unit is called a Class.
Answer: ( 3 marks for explanation, 2 marks for example with output) 2) Encapsulation enables data hiding, hiding irrelevant information from users of a class and obj_bird.intro()
exposing only the relevant details required by the user. obj_bird.flight()
Init or initialize Method (Creating constructor): 3) One can declare the methods or the attributes protected by using a single underscore ( _ ) obj_parr.intro()
• Constructors are generally used for instantiating an object. before their names. Such as- self._name or def _method( ); Both of these lines tell that the obj_parr.flight()
• The task of constructors is to initialize (assign values) to the data attribute and method are protected and should not be used outside the access of the class obj_peng.intro()
members of the class when an object of class is created. and sub-classes but can be accessed by class methods and objects. obj_peng.flight()
• In Python the init () method is called the constructor and is always 4) Though Python uses ‘ _ ‘ just as a coding convention, it tells that you should use these
called when an object is created. attributes/methods within the scope of the class. Output:
5) For actually preventing the access of attributes/methods from outside the scope of a class, There are different types of birds
Most of the birds can fly but some cannot
Syntax of constructor declaration : you can use “private members“. In order to declare the attributes/method as private
There are different types of bird
def init (self): members, use double underscore ( ) in the prefix. Such as – self. name or def Parrots can fly
# body of the constructor method(); Both of these lines tell that the attribute and method are private and access is There are many types of birds
not possible from outside the class. Penguins do not fly

b) With the help of an example explain the significance of the init () method or
Example: For creating constructor use init method called as constructor. ii) Polymorphism: (at least 3 correct point with definition) constructor. [5]
1) This is a Greek word. If we break the term Polymorphism, we get “poly”-many and Answer:
class student: “morph”-forms. So Polymorphism means having many forms. In OOP it refers to the
def init (self,rollno,name,age): (Mistakenly repeated question, refer Q5 (c) for answer)
functions having the same names but carrying different functionalities.
print("student object is created") 2) It allows one interface to be used for a set of actions. It means same function name(but c) Write a python program that uses class to store exam number and marks of four
p1=student(11,"Ajay",20) different signatures) being used for different types. subjects. Use list append to store the marks of four subjects. [7]
print("Roll No of student= ",p1.rollno) 3) When the function is called using the object audi then the function of class Audi is
print("Name No of student= ",p1.name) Answer:
called and when it is called using the object bmw then the function of class BMW is
print("Age No of student= ",p1.age) called.
4) Its simple example can be taken as, a who is working as an employee in office, but at
Output: home he has the roles of a father, a son, a brother etc.
student object is created
Roll No of student= 11 Example:

File: • Typically, computer users deals with binary files more than text files. Unlike text file, in
binary file there is no EOL symbol.
1. File is storage space for data or information. File is nothing but an object that preserves
data or information. • Common extensions that are in Binary file formats as following
2. Every file is having a name “filename”. 1. Images: jpg, png, gif, bmp, tiff,.…
3. For creating files you can use multiple softwares available in the computer. For example 2. Videos: mp4, mkv, avi, mov, mpg, vob….
you can use text editor to create text file.
3. Audio: mp3, aac, wav, flac, ogg, mka, wma….
4. Whenever file is saved, it has two aspects associated with it.
4. Documents: pdf, doc, xls, ppt, docx, odt…..
1. The file name
5. Archive: zip, rar, 7z, tar, iso….
2. The extension of the file
6. Databases: mdb, accde, frm, sqlite,….
5. In computer system file can be of two types
7. Executable: exe, dll, so, class….
1. Text File
• Unlike text files, binary files need same software to read the file which is used to create
2. Binary File the file. Binary files need matching softwares for reading and writing.
Output: Text File: c) Define dictionary with syntax. Enlist any four dictionary methods. [5]
Name: Mathews
Roll no: 3 • The file which is in human readable form, where each line ends with EOL symbol(\n) by Answer:
Division: A
Enter the marks of respective subjects: default.
Engineering Physics: 50
1. Dictionaries are defined in terms of key-value pairs. Usually keys are defined in terms of
Engineering Mathematics: 40 • We use various text files like program source code, setup scripts, technical strings/numbers. But value can be of any type.
Basic Electrical Engineering: 70 documentation, program generated output and logs, configuration files. 2. Dictionaries are closed in curly braces and are mutable data type.
Programming and Problem Solving: 80
3. At time of accessing key, if key is not present it will generate “Keyerror”.
name: Mathews
Roll no: 3
• Common extensions that are in text file formats as following
Any Four Dictionary Methods:
Division: A
Marks: ['50', '40', '70', '80'] 1. Webstandards: html, xml, css, svg, json… a. Clear (): Removes all the elements from the dictionary.
2. Source code: c, cpp, h, cs, js, py, java, rb…. b. copy () Returns a copy of the dictionary
Q7) a) Write a python program that reads data from one file and write into another file. [6] c. items () Returns a list containing a tuple for each key value pair
Answer: (6 marks just to write correct program) 3. Documents: txt, tex, asciidoc,…. d. keys () Returns a list containing the dictionary's keys
4. Tabular Data: csv, tsv…. e. pop() Removes the element with the specified key
with open (‘ice and fire.txt’) as f:
• For opening text file we need text editor. We can use different editors for creating and OR
with open (‘out.txt’, ‘w’) as f1:
viewing text file i.e. we can create text file in one type of editor and open same file in Q8) a) Explain the method to open a text file as well as write down the file modes in which
for line in f: another one. files can be opened. [6]
f1.write(line) Binary File: Answer:
• In this type of files data is represented in the machine understandable format. Hence these For opening a file, python is provided with a built in function called as “open()”.
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
b) Define files and enlist types of files with multiple examples. [6] media players.
Function Description
Answer: (2 marks for definition and 2 marks each for enlisting types)
mode
r Open file in read mode if file not present then it will raise the error https://t.me/sppu_fe_solve_paper Join our Telegram.
w Open file in write mode, if file does not present it will create a file and Output:
open it in write mode. The contents of dictionary are: {'name': 'Bob', 'Age': 21, 'Marks': 88.0)
a Append new contents at the end of existing file. If file is not present it will Modified contents of dictionary are: {'name': 'Bob', 'Age': 21, 'Marks': 88.0, 'City':
create a file and open it in append mode. 'London'}
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)

You might also like