You are on page 1of 28

MODEL QUESTION PAPER-1

Max Marks: 60
Time: 2 1/2 Hours
Instruction: Answer any 4 Questions from each Part
PART-A
I. Answer any Four questions. Each question carries 2 Marks. (4×2=8)
1. What is the purpose of indentation in Python?
Python indentation refers to adding white space before a statement to
a particular block of code. In another word, all the statements with the
same space to the right, belong to the same code block.
If proper indentation is not given then we will end up seeing
indentation errors and the code will not get compiled.

2. Define the "if..elif..else" decision control statement in Python.


The if else statement is used to execute a block of code among two
alternatives. However if we in to make a choice between more than
two alternatives, then we use the if elif else statement The if elif else
statement is a multi-way decision maker which contains two or more
branches from which any one block is executed.
Example:

marks = int (input("Enter the marks :"))


if marks> 85 and marks <=100:
print("Congrats! You scored grade A")
elif marks>60 and marks<=85:
print("You scored grade B+")
elif marks> 40 and marks <=60
print("You scored grade B")
elif marks>30 and marks<=40
print("You scored grade C")
else print("Failed")

Output:
Enter the marks 89 Congrats!! You scored grade A
Enter the marks: 67
You scored grade B+
Enter the marks:14
Failed

3. What is the difference between a list and a tuple in Python?

SR.NO. LIST TUPLE

1 Lists are mutable Tuples are immutable

The implication of iterations is Time- The implication of iterations is


2 consuming comparatively Faster
SR.NO. LIST TUPLE

The list is better for performing


operations, such as insertion and Tuple data type is appropriate
3 deletion. for accessing the elements

Tuple consumes less memory


4 Lists consume more memory as compared to the list

4. Explain the built-in functions used on dictionaries in Python


1) len(): The len() function returns the number of items (key:value
pairs) in a dictionary.
Syntax: len(dictionary_name)
>>> myDict = {1: 'A', 2: 'B', 3: 'C', 4: 'D'}
>>> len (myDict)
4

2) any(): The any() function returns Boolean True value if any of the key
in the dictionary is True else returns False.
Syntax: any(dictionary_name)
>>> myDict = {1: 'A', 2: 'B', 3: 'C', False: 'D'}
>>> any (myDict)
True
>>> myDict = {0: 'A', False: 'B'}
>>> any (myDict)
False

3) all(): The all function returns Boolean True value if all the keys in the
dictionary are True else returns False.
Syntax: all(dictionary_name)
>>> myDict = {1: 'A',2: 'B',3: 'C',4: 'D'}
>>> all (myDict)
True
>>> myDict = {1: 'A',2: 'B',0: 'C', False: 'D'}
>>> all (myDict)
False

5. What is the difference between class attributes and data attributes in


object-oriented programming?
6. What is the purpose of using Matplotlib for data visualization in
Python?
Matplotlib is a low-level library of Python which is used for data
visualization. It is easy to use and emulates MATLAB like graphs and
visualization.
This library is built on the top of NumPy arrays and consist of several
plots like line chart, bar chart, histogram, etc.
It provides a lot of flexibility but at the cost of writing more code.
PART-B

II. Answer any Four questions. Each question carries 5 marks. (4x5=20)
7. Explain the steps to create and read a text file in Python.
"x" – Create: this command will create a new file if and only if there is
no file already in existence with that name or else it will return an error.
Example:
#creating a text file with the command function "x"
f = open("myfile.txt", "x")

"r" – Read:
This function returns the bytes read as a string. If no n is specified, it
then reads the entire file.
Example:
f = open("myfiles.txt", "r")
#('r’) opens the text files for reading only
print(f.read())
#The "f.read" prints out the data in the text file in the shell when run.

8. Discuss the use of inheritance in object-oriented programming in


Python.
Inheritance is an important aspect of the object-oriented paradigm.
Inheritance provides code reusability to the program because we can
use an existing class to create a new class instead of creating it from
scratch.

In inheritance, the child class acquires the properties and can access all
the data members and functions defined in the parent class. A child
class can also provide its specific implementation to the functions of
the parent class.

In python, a derived class can inherit base class by just mentioning the
base in the bracket after the derived class name. Consider the following
syntax to inherit a base class into the derived class.

Syntax
class derived-class(base class):
<class-suite>

Example
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()

Output:
dog barking
Animal Speaking

9. Explain the relation between tuples and lists in Python.


Relation between Tuple and Lists

List and tuple are data structures in Python. Both lists and tuples are
used for storing objects in pythonThough tuples may seem similar to
lists, they are often used in different situations and for different
purposes. Let us understand the relation between tuple and list with
some examples.

Tuples are immutable, and usually, contain a heterogeneous sequence


of elements that are accessed via unpacking or indexing. Lists are
mutable, and their items are accessed via indexing. Items cannot be
added, removed or replaced in a tuple.

Converting Tuple to List and List to Tuple


The tuple can be converted to list using list() function by passing tuple
as an argument
Once it is converted to the list, the contents in the list can be modified
or altered.
Finally, we can convert the updated list into tuple by using tuple
function by passing the updated list as an argument

Converting Tuple to List and List to Tuple

Example:
#create a tuple
languages = ("Python", "Java","PHP")
# print tuple contents
print ("Tuple Items", languages)
#convert tuple to list
LanguageList =list(languages)
#print list contents
print ("List Items: "LanguageList)
#update list
LanguageList[e] "VB.NET"
#print list contents
print ("List Items: Languagelist)
#convert list to tuple
languages = tuple (LanguageList)
#print tuple contents
print ("Tuple Items : ",languages)

Output:
Tuple Items: ('Python', 'Java','PHP')
List Items: ['Python', 'Java', 'PHP']
List Items: ['VB.NET', 'Java', 'PHP']
Tuple Items: ('VB.NET', 'Java', 'PHP')

List as an element in Tuple


We know that tuple can hold objects of any type. It means that we can
have list, string, dictionary as an item inside a tuple. If an item within a
tuple is mutable, then we can change it.
Example
A List as an items in a Tuple
#create a list
myList = ["one", "two", "three"]
#print list contents
print("List Items: \n ",myList)
#create a tuple. A tuple as an item in it
myTuple = (10,20,30, myList)
#create tuple contents
print("Tuple items: \n",myTuple)
#update list by adding new item
myList.append("four")
#print list contents
print("Update List Items: \n",myList)
#print tuple contents
print ("Update List in Tuple: \n", myTuple)

Output:
List Items:
['one', 'two', 'three']
Tuple Items:
(10,20,30, ['one', 'two', 'three'])
Update List items:
['one', 'two', 'three', 'four']
Update List in Tuple:
(10,20,30, ['one', 'two', 'three', 'four'])

10. Explain the constructor method in object-oriented programming in


Python.
A constructor is a special type of method (function) which is used to
initialize the instance members of the class.
Constructors can be of two types.
Parameterized Constructor
Non-parameterized Constructor
Constructor definition is executed when we create the object of this
class. Constructors also verify that there are enough resources for the
object to perform any start-up task.
In Python, the method the __init__() simulates the constructor of the
class. This method is called when the class is instantiated. It accepts the
self-keyword as a first argument which allows accessing the attributes
or method of the class.

Example
class Employee:
def __init__(self, name, id):
self.id = id
self.name = name
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
emp1 = Employee("John", 101)
emp2 = Employee("David", 102)
# accessing display() method to print employee 1 information
emp1.display()
# accessing display() method to print employee 2 information
emp2.display()
Output:
ID: 101
Name: John
ID: 102
Name: David

11. Explain the purpose of using Web APIs for data visualization in
Python. Explain with an example.
An API (Application Programming Interface) is a set of protocols,
routines, and tools for building software and applications. It specifies
how software components should interact and APIs allow
communication between different systems or platforms. An API
provides a way for one software application to access and use the
features or data of another application

An API acts as an intermediary between two systems, allowing one


system to access the data or functionality of another An API defines the
set of rules for making requests and receiving responses between the
two systems A Web API is a type of API that is hosted on the web and
accessed over the internet using standard web protocols such as HTTP
A Web API is used to allow communication between a web application
and a server It is designed to provide an interface for web applications
to interact with a server, making it possible for a web application to
access resources and data from a server and vice versa.
Example: If someone wants to build a weather application, they can use
a weather API to access and retrieve weather data from a source such
as a government weather agency. The API provides the necessary
functions for the application to access the weather data, saving the
developer the time and effort of building a system to collect the
weather data from scratch.

12. Discuss the steps to install Plotly and generate a line graph in
Python.
Installing Plotly
The step-by-step process of installing Plotly using pip in the command
prompt
1 Open the command prompt
2 Type in the following command to install plotly and plotly.express.
Install one by one
To install plotly: pip install plotly
To install plotly express: pip install plotly express
3. Press the Enter key to execute the command. This will start the
installation process for Matplotlib.
4Wait for the installation process to complete. We should see a
message indicating that plotly and plotly express has been successfully
installed
5 To verify the installation, we can type in the following command:
pip show plotly
pip show plotly.express
6. This should display information about the installed version of plotly
and plotly.express, including its location and version number
7. We can now start using plotly in a Python projects. To use plotly and
plotly express in a code. we need to import the library using the
following line of code:
import plotly
import plotly.express as px

PART-C

III. Answer any Four questions. Each question carries 8 marks. (4x8=32)
13. (a) Explain the purpose of the "return" statement in Python.
(b) Discuss the steps to install and use the Pickle module in Python.
(a) A return statement is used to end the execution of the function call
and “returns” the result (value of the expression following the return
keyword) to the caller. The statements after the return statements are
not executed. If the return statement is without any expression, then
the special value None is returned. A return statement is overall used to
invoke a function so that the passed statements can be executed.
Syntax:
def fun():
statements
.
.
return [expression]
Example:
# Python program to
# demonstrate return statement
def add(a, b):
# returning sum of a and b
return a + b
def is_true(a):
# returning boolean of a
return bool(a)
# calling function
res = add(2, 3)
print("Result of add function is {}".format(res))
res = is_true(2<5)
print("\nResult of is_true function is {}".format(res))
Output:
Result of add function is 5
Result of is_true function is True

(b) Pickle is part of the standard library, so there is no need to pip install
it.
Python pickle module is used for serializing and de-serializing a Python
object structure. Any object in Python can be pickled so that it can be
saved on disk. What pickle does is that it “serializes” the object first
before writing it to file. Pickling is a way to convert a python object (list,
dict, etc.) into a character stream. The idea is that this character stream
contains all the information necessary to reconstruct the object in
another python script.
The pickle module is used for implementing binary protocols for
serializing and de-serializing a Python object structure.
Pickling: It is a process where a Python object hierarchy is converted
into a byte stream.
Unpickling: It is the inverse of Pickling process where a byte stream is
converted into an object hierarchy.
Module Interface :
dumps() – This function is called to serialize an object hierarchy.
loads() – This function is called to de-serialize a data stream.

14. (a) Define the "while" loop in Python.


(b) Explain the use of the "zip" function in Python.
(a) Python While Loop is used to execute a block of statements
repeatedly until a given condition is satisfied. And when the condition
becomes false, the line immediately after the loop in the program is
executed.

Syntax:
while expression:
statement(s)

Example:
# Python program to illustrate
# while loop
count = 0
while (count < 3):
count = count + 1
print("Hello from Python")
Output:
Hello from Python
Hello from Python
Hello from Python

(b) Python zip() method takes iterable or containers and returns a single
iterator object, having mapped values from all the containers.
It is used to map the similar index of multiple containers so that they
can be used just using a single entity.
Syntax : zip(*iterators)
Parameters : Python iterables or containers ( list, string etc )
Return Value : Returns a single iterator object, having mapped values
from all the containers.

Example:
name = [ "Manjeet", "Nikhil", "Shambhavi", "Astha" ]
roll_no = [ 4, 1, 3, 2 ]
# using zip() to map values
mapped = zip(name, roll_no)
print(set(mapped))

Output:
{('Shambhavi', 3), ('Nikhil', 1), ('Astha', 2), ('Manjeet', 4)}
15. (a) Discuss the different ways to create a dictionary in Python.
(b) Explain the difference between a dictionary and a set in Python.
(a) There are two main way of creating a dictionary.
Creating Dictionary by Using Curly Braces ().
Creating Dictionary by Using dict() Function.
Creating Dictionary by Using Curly Braces {}
To create a dictionary, the items entered are separated by commas and
enclosed in curly braces Each item is a key value pair, separated
through colon (). The left of the colon operator are the keys and the
right of the colon operator are the values. The keys in the dictionary
must be unique and should be of any immutable data type, i.e.,
number, string or tuple. The values can be repeated and can be any
data type.
Syntax:
dictionary_name = {} # It is empty dictionary
dictionary_name = { key_1: value_1, key_2: value_2, key_3 : value 3....}

Example: Creating Dictionary with Key Value Pairs


#person is the dictionary that maps names of the person to respective
age
>>>person = {'Srikanth': 44, 'Bhagya': 42, 'Snigdha': 19, 'Rakshith': 24}
>>>person
{'Srikanth': 44, 'Bhagya': 42, 'Snigdha': 19, 'Rakshith': 24}
Creating Dictionary by Using dict() Function.
The Python dict() is a built-in function that returns a dictionary object or
simply creates a dictionary
Syntax:
dict (**kwargs)
dict (mapping, **kwargs)
dict (iterable, **kwargs)

Example:
Creating Dictionary Using dict(**kwargs)
>>>#creating empty dictionary
>>>my_dictionary = dict()
>>>my_dictionary
{}
>>>#creating dictionary with keyword arguments
>>>my_dictionary = dict(a=10,b=20,c=30)
>>>my dictionary
{'a': 10, 'b': 20, 'c'=30}

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


(b) Explain the process of polymorphism in object-oriented
programming in Python
(a) The tell() method in Python returns the current position of the file
pointer within a file. It returns position of the file pointer.
Syntax: file object.tell()
Here, file object is a file object returned by the open() method, and
tell() is the method used to get the current position of the file pointer.
Example:The tell() method
#Open the file in read mode
with open("myFile.txt", "r") as file:
print("Current position:", file.tell())
contents = file.read(5)
print("Current position after reading 5 bytes:", file.tell())
contents file.read(5)
print("Current position after reading another 5 bytes:, file.tell())
Output:
Current position: 0
Current position after reading 5 bytes: 5
Current position after reading another 5 bytes: 10

(b) The purpose of the seek() method in Python is to allow for random
access in a file. The seek() method in Python is used to move the file
pointer to a specified position within the file.

Syntax: file_object.seek(offset, whence)


Eample:
#open the file in write mode
with open("file_new.txt", "w+") as fObj:
fObj.write("Hello, Srikanth!")
fobj.seek(0)
print("File Contents Before Modification : ", fobj.read())

fobj.seek(6)
fobj.write("Mr.")

fobj.seek(0)
print("File Contents After Modification:", fObj.read())

Output:
File Contents Before Modification: Hello,Srikanth!
File Contents After Modification: Hello, Mr.kanth!

17. (a) Explain the Duck Typing in Python


(b) Discuss the use of the Frozenset in Python.
(a) Duck typing is a concept in dynamic programming languages like
Python, where the type of an object is determined by its behavior
rather than its class definition. In duck typing, the type of the object is
not checked at compile-time, but rather at run-time. The means that if
an object has the required methods or properties, it is considered as an
instance of specific type, even if it doesn't belong to that type.
Example: Duck Typing (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 func(obj):
obj.type()
obj.color()

Output:
SUV
Black
Fruit
Red
(b) The frozenset() function returns an Immutable frozenset object
initialized with elements from the en iterable. Frozen set is just an
immutable version of a Python set object. While elements of a set an
be modified at any time, elements of the frozen cannot be modified or
altered after its creation As frozen sets are immutable, the frozen sets
can be used as keys in Dictionary or as elements of other set.
Syntax:
frozenset([iterable])

Example:
#creating a dictionary
Student = ("name": "Ankit","age": 21, "ID": 1681)
#making keys of dictionary as frozenset
key= frozenset (Student)
#printing dict keys as frozenset
print('The frozen set is:', key)

Output:
The frozen set is: frozenset({'age', 'name', '10'))

18. (a) Explain the use of the "continue" and "break" statements in
Python.
(b) Discuss the process of data visualization using Plotly and JSON
format in Python.
(a) The break statement is used to terminate the loop or statement in
which it is present. After that, the control will pass to the statements
that are present after the break statement, if available. If the break
statement is present in the nested loop, then it terminates only those
loops which contains break statement.
Syntax:
break
Example: The break in for loop
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

Continue is also a loop control statement that forces the loop to


continue or execute the next iteration. When the continue statement is
executed in the loop, the code inside the loop following the continue
statement will be skipped and the next iteration of the loop will begin.
Syntax:
continue
Example: To print numbers from 0 to 5 except 3
for i in range(6):
if i==3:
continue
print(i)
Output:
1
2
4
5

(b) A step-by-step process for visualizing data from a JSON file using
Python is shown below.
1. Create JSON: This step involves creating the ISON file that will store
the data to visualize We can create the JSON file using a text editor or
using code in Python
2. Load JSON: Once we have created the ISON file, we can load it into
Python using the json module. This module provides functions for
reading and parsing 150N data, making it available for analysis.
3. Extract and parse data: In this step, we will extract the data from the
JSON file and pare it into a format that is suitable for visualization. To
do this, we can use the json.load function to read the data from the file,
and then use Python's built in data structures, such as lists and
dictionaries, to organize the data.
4. Use Plotly or Matplotlib to visualize data: Once we have extracted
and parsed the data, we can use a visualization library like Plotly or
Matplotlib to create visualizations.
5. Customize the visualization: Once WE have created the visualization.
We can customize it to suit our needs. This may involve adding labels,
changing colors, adjusting the axis scales, and more.
6. Interact with the Visualization: To get the most out of visualization,
we should be able to interact with it. Plotly provides a range of
interactive options, such as zooming, panning and hover effects, that
we can use to interact with the visualization. Matplotlib also provides
some interactive options, but they are more limited
7. Save and share the visualization: Finally, we can save the
visualization to disk share it online, or embed it in a web page or other
document. To save the visualization to disk, we can use the savefig
function in Matplotlib or the write image function in Plotly

You might also like