Professional Documents
Culture Documents
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.
Output:
Enter the marks 89 Congrats!! You scored grade A
Enter the marks: 67
You scored grade B+
Enter the marks:14
Failed
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
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.
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
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.
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')
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'])
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
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.
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 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}
(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.
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!
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
(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