0% found this document useful (0 votes)
49 views11 pages

PYTHON (Model Paper-01)

Uploaded by

Apoorva Kanade
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)
49 views11 pages

PYTHON (Model Paper-01)

Uploaded by

Apoorva Kanade
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/ 11

PYTHON

MODEL QUESTION PAPER-01

❖ ANSWER THE FOLLOWING QUESTIONS: (ANY 6) (2*6=12)

01. What is purpose of indentation in python?


ANS: indentation in python is not used for styling but rather it is the requirement for
python code to get compiled and executed

02. Define the “if…elif…else” decision control statement in python?


ANS: The “if…elif…else” statement is a multi-way decision maker which contains two or
more branches, from which any one block is executed.

03. What is the difference between a list and a tuple in python?


ANS:
LIST TUPLE
• Lists are mutable • Tuples are immutable
• The implementation of iteration is • The implementation of iteration is
time consuming comparatively faster
• The list is better for performing • Tuple data type is appropriate for
operations, such as insertion & accessing the elements
deletion
• Lists consume more memory • Tuple consume less memory
• Lists have several built-in methods • Tuple does not have many built-in
functions
• The unexpected changes and • In tuple, it is hard to take place
errors are more likely to occur

04. Explain built-in-functions used on dictionaries in python?


ANS:
Built-in-function description
Len() The len() function returns the number of items.
Syntax: len(dictionary_name)
any() The any() function returns Boolean true values if any key
in the dictionary is true else returns false.
Syntax: any(dictionary_name)
all() The all() function returns Boolean true values if all key in
the dictionary is true else returns false.
Syntax: all (dictionary_name)
sorted() The sorted() function returns a sorted list of the specified
iterable object.
05. What is the difference between class attributes and data attribute in object-oriented
programming?
ANS:
CLASS ATTRIBUTES DATA ATTRIBUTES
• They are used to store values that • They are used to store values that
are common to all objects are unique to each object
• Declared outside the constructor • Declared inside the constructor
• Same value for all objects • Different values for all objects
• Memory is allocated only once • Memory is allocated for each
object
• It can be modified by any object in • It can be modified only by the
the program object that created them
• They are typically initialized when • They are initialized when an
the class is defined object is created in __init__
method
• They can be accessed by any • They can be accessed only by the
object in the program object that created them

06. What is purpose of using matplotlib for data visualization in python?


ANS:
• It provides a function for creating static, animated and interactive visualization in
2D or 3D.
• It is used for data visualization, data analysis and scientific computing in various
domains.
• It provides a number of built-in plots, including line plots, bar plots, scatter plots,
histogram etc.

❖ ANSWER THE FOLLOWING QUESTIONS: (ANY 4) (5*4=20)

07. Explain the steps to create and read a text file in python?
ANS:
• Python provides build-in-functions to create or write and to read the files so there is
no need of importing libraries like we do in JAVA.
Create or write text file:
• To create or write the text file in python Open() built-in function is used.
• This method accepts many arguments but majority of time we use only two,
• We have multiple modes, but here we are using “w” mode because we are writing
the text file.
• After creating the file it is importing to close the file by using close() method.
Example: file_open(“file name”,’mode’)
Program: file = open(“myfile_text”,”w”)
File. Write(“data to enter in file”)
File. Close()
(OR)
With open(“myfile.txt”,”w”)as file
File. Write(“data to enter in file”)
Read text file:
• To read the text file, we use the open() function in similar manner as for writing the
file.
• We use “r” mode to read the text file.
• The content of file can be read using the read() method.
• After reading the file it is important to close the file using close() method.
Example:
File = open (“myfile.txt”, “r”)
Content = file. Read()
Print(content)
File. Close()
Output:
This is the first line
This is the second line

08. Discuss the use of inheritance in python?


ANS:
• The main use of inheritance is to reuse existing code and to extend its
functionality in the sub class.
• It helps to reduce the amount of code that provides code modularity, promotes
the code reusability.
• It makes easier to maintain and update the code.
• It also enables the creation of hierarchical class structure.

09. Explain the relation between tuples and lists in python?


ANS:
Tuples:
Tuples are immutable, and usually contains a heterogeneous sequence of elements that
are accessed via unpacking or indexing.
Example:
Tuple = (“summer”)
Print (“initial tuple:”)
Tuple[1] = “winter”
Print (“Tuple:”)
Output:
Initial tuple: summer
Error (because tuples cannot be changed they are immutable)

Lists:
Lists are mutable, and their items are accessed via indexing. Items cannot be added,
removed or replaced in a tuple.
Example:
List = [2, 3, 5, 6]
Print (“initial list:”)
List [2] = 4
Print (“list:”)
Output:
Initial list: [2, 3, 5, 6]
List: [2, 3, 4, 5, 6]

10. Explain the constructor method in python?


ANS:
• Constructor method is a special method that is called when the object is created.
• It is used to initialize the object’s properties or instance variables or class
attributes of a class.
• The constructor method is called __init__ and defined within a class.
• The __init__ method takes at least one argument, this argument is typically
called self.
Syntax:
__init__(self, [arg1, arg2, ….])
Example:
Class circle
Def __init__(self, radius) :
Self.radius = radius

Def area(self):
Return 3.14 * self.radius**2
Def circumference(self):
Return 2 * 3.14 * self.radius
Circle = circle(10)
Print(“Radius:”, circle.radius)
Print(“area:”, circle.area())]
Print(“circumference:”, circle.circumference())
Output:
Radius: 10
Area: 314.0
Circumference: 62.800000000000004

11. Explain the purpose of using web APIs for data visualization in python. Explain with
an example?
ANS:
• Web APIs are very useful in implementation of RESTFUL web services using NET
frame work.
• Web API helps in enabling the development of HTTP services to reach out to
client entities like browser, devices or tablets.
• ASP.NET web API can be used with MVC for any type of application.
• A web API can help you develop ASP.NET application via AJAX.
• Hence, web API makes it easier for the developer to build an ASP.NET application
that is compatible with any browser and almost any device.

12. Discuss the steps to install plotly and generate a line graph in python?
ANS:
Steps to install the plotly:
• Open the command prompt
• Type pip install plotly command to install it
• Press the enter key to execute the command. This will start the installation
process.
• Wait for the installation process to complete.
• Once it is completed, we can type pip show plotly to verify the installation.
• This should display information about the installed version of plotly including its
location and version number.
• Now we can use the plotly, but to use plotly in code, we need to import the
library using import import plotly


• Simple line plot between X and Y data

❖ ANSWER THE FOLLOWING QUESTIONS: (ANY 4) (8*4=32)

13. (a) Explain the purpose of the return statement in python?


ANS:
The function return statement is used to exit from a function and go back to
the function caller and return the specified value or data item to the caller.
Syntax: return (expression_list)
The return statement can consist of variable, an expression, or a
constant which is returned to the end of the function execution. If none of
the above is present with the return statement a none object is returned.
Example:
Python function for return statement
def square_value(num)
this function returns the square value of the entered number
return num**2
print (square_value(2))
print(square_value(-4))
Output:
4
16

(b) Discuss the steps to install and use the pickle module in python?
ANS: python pickle package is used for serializing and de-serializing a python object
structure. Any object in python can be pickled so that it can be stored on the local
disk.
Steps to install pickle module on linux using PIP :
Step 1: The first step we will use the apt manager to install python 3
Step 2:to install any python package, we’ll require a PIP manager, which is a python
package installation program. The installation of the PIP manager using apt is
described in the steps below.

Step 3:in this step, we’ll actually us e the PIP manager to install the pickle package.
To install the pickle package, simply run the command below on the terminal.

Step 4: the next step is to double-check it, so that we can only use the terminal to
get the information about the installed pickle package.

14. (a) Define the while loop in python?


ANS: While loop is used to execute the block of codes repeatedly until a given
condition is satisfied and when the condition becomes false, the control comes out
of the loop.
Syntax: while (expression)
Example:
Count = 0
While (count<2)
Count = count+1
Print(“helloworld”)
Output:
Helloworld
Helloworld

(b) Explain the use of the ZIP () function in python?


ANS: zip is a built-in-function that takes two or more sequences and “zips” then into
a list of tuples, where each tuple conatains one element from each sequence. In
python, zip returns an iterator behaves like a list.
Syntax: Zip(* iterator)
Example: python zip () two lists
name = [“manjeet”, “Nikhil”, “shambhavi”, “astha”]
roll_no = [4, 1, 3, 2]
mapped = zip (name, roll_no)
print (set (mapped))
output:
{(‘shambhavi’,3), (‘nikhil’,1), (‘astha’,2), (‘manjeet’,5)}

15. (a) Discuss the different ways to create a dictionary in python?


ANS: Dictionary can be created using curly braces {} separated by commas, it can
also be created by the built-in-function dict().

Program to demonstrate the creation of dictionary:


Dict={}
Print(“empty dictionary”)
Print(dict)

#creating dictionary with the use of mixed keys:


Dict={‘name’: ‘python’,1:[1,2,3,4]}
Print(“\n dictionary with the use of mixed keys:”)
Print(dict)

#creating dictionary with the use of dictionary:


Dict= dict([1: ’python’, 2: ’for’, 3 ‘life’])
Print(“\n dictionary with the use of dict():”)
Print(dict)

#creating dictionary with each item as a pair:


Dict=dict([(1,’python’), (2, ‘for’)])
Print(“\n dictionary with each item as a pair:”)
Print(dict)

(b)Explain the difference between dictionary and a set in python?


ANS:
Set Dictionary
It is the unordered collection of data It is the ordered collection of key-value
type that are iterable pairs
It is mutable It is also mutable
It doesn’t supports indexing It supports indexing
Can be created using set() function Can be created using dict() function
They are represented in curly braces{} They are also represented by {}
Duplicate elements are not allowed Duplicate elements are not allowed for
keys, but values can be duplicated

16. (a)Explain seek () and tell () with example?


ANS: Seek()
• The purpose of the seek() method in python is to allow for random access in
a file.
• the seek() method is used to move the file pointer to a specified position
within the file.
• This allows to perform operation such as inserting, updating and deleting
specific portions of a file.
• The seek() method has two arguments: an “off set value” and “whence”
arguments that specifies the starting point from the where the offset is
applied

Syntax: file_object.seek(offset, whence)


Example:
With open (“file_new. txt”, “w+”) as file:
file.write (“hello,srikanth!”)
file.seek(0)
print(“file contents before modification:”,file.read())
file.seek(6)
file.write (“mr.”
file.seek(0)
print(“file contents after modification:”,file.read())
output:
file contents before modification: hello, srikanth!
file contents after modification: hello, mr.srikanth!

(b)Explain the process of polymorphism in python?


ANS:
• Polymorphism is the condition of occurrence in the different forms.
• It is refers to the use of the same function name, but with different
signatures, for multiple types.

Program to demonstrate in built polymorphic functions:

#len () being used for a string


Print (len (“python”))
#len () being used for a list
Print (len ([10, 20, 30]))
Output:
6
3

Program to demonstrate polymorphism using user-defined function:

Def add(x, y, z=0)


Return x+y+z
#driver’s code
Print (add (2, 3))
Print (add (2, 3, 4))
Output:
5
9

17. (a)Explain the Duck typing in python?


ANS:
DUCK TYPING:
• Duck typing is a concept of dynamic programming languages like python,
where the type of an object is determined by its behavior rather than its
class.
• In other words, it is based on the ideas that “if it walks like a duck and quacks
like a duck, it is a duck”
• In duck typing , the type of the object is not checked at compile time, ut
rather at run-time.
• It is considered as an instance of a specific type, even if it doesn’t belong to
that type.
Program to demonstrate Duck typing in polymorphism with function and
objects:

Class car:
Def type(self):
Print(“SUV”)
Def color(self):
Print(“black”)
Class Apple:
Def type(self):
Print(“fruit”)
Def color(self)
Print(“red”)

Def fun(obj):
obj.type()
obj.color()

obj_car = Car()
obj_apple = Apple()
Fun(obj_car)
Fun(obj_apple)
Output:
SUV
Black
Fruit
red

(b)Discuss the use of the frozenset in python?


ANS: frozen set:
• Python frozen set() method creates an immutable set object from an
iterable.
• It is a built-in python function. As it is a set object therefore we cannot have
duplicate values in the frozen set.
Syntax:
frozenset(iterable_object_name)
➢ Parameter: iterable_object_name: this function accepts iterable objects as
input parameter
➢ Return: retuns an equivalent frozen set object

Example:
Vowels ={‘a’, ‘e’, ‘I’, ‘o’, ‘u’}
fset= frozenset(vowels)
Print(fset)
Output:
Frozenset({‘I’, ‘o’, ‘u’, ‘e’, ‘a’})
Program to demonstrate frozenset using method tuple:
Tuple=()
Fnum= frozenset(tuple)
Print(“frozen object is:”, fnum)
Output:
Frozenset object is : frozenset()

18. (a)Explain the use of “continue” and “break” statements in python?


ANS: the continue statement:
The continue statement is used to skip the rest of the statements in the current
loop block and to continue to the next iteration of the loop. Instead of terminating
the loop like a break statement it moves on the subsequent execution.
Example:
For I in range(6):
If I == 3:
Continue
Print(i)
Output:
0
1
2
4
5

Break statement:
The break statement or keyword is used to terminate the loop. A break statement is
used inside both the while and for loops. It terminates the loop immediately and
transfers the execution to the immediate statement after the loop.
Example:
For I in range(1,10):
If i==5:
Break
Print(i)
Print(“out of the loop”)
Output:
1
2
3
4
Out of the loop

(b)Discuss the process of data visualization using plotly and JSON format in python?
ANS:

You might also like