Professional Documents
Culture Documents
Pps Micro
Pps Micro
Pps Micro
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:
Ans:
4) What is Lambda function? Write a program that uses Lambda function to multiply two numbers.
Ans: Ans:
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
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
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
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:
17) Define programming paradigm. List programming paradigms. Explain any three.
• 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
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.
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")
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"}
print(a) • print(di.keys())
o/p: dict_keys([1, 2, 3])
a=f.read(7) • print(di.get(1))
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
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):
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}
dict2['City']='London'
print('Modified contents of dictionary are:\n',dict2)