You are on page 1of 19

PYTHON

MODEL QUESTION PAPER-02

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

01. Why python is called as multi-paradigm programming language?


Ans: python is called as multi-paradigm programming language because it supports object
oriented, procedure oriented, functional programming and imperative programming
language.

02. What is a keyword and literals in python?


Ans: keyword: they are predefined, reserved words used in python that have special
meaning to the complier. We cannot use a keyword as a variable name, function name or
any other identifier. They are used to define the syntax and structure of the python
language
Literals: ut means the value or data which is assigned to the variables. They are the
representation of fixed values in a program. They can be numbers, characters or strings etc.

03. Explain the concept of indexing and slicing in list?


Ans: indexing list:
• Each individual element in a list can be accessed using a technique called indexing.
• The index specifies the element to be accessed in the list and is written in []
• The index of the first element(from left) in the list is 0 and the last element is n-1,
where n is the length of the list.
Example:
List=[10, 20, 30, 40, 50]
For I in range(0, len(list)):
Print(list[i])
Output:
10
20
30
40
50

Slicing list:
• in python, to access some part of the list or sublist, we use a method called
slicing.
• The slicing operator [start : end] is used for slicing.
• This can be done by specifying an index range.
• The slice operation list[start : end] returns the part of the list starting from the
index start and ending at end.
Example:
List = [10, 20, 30, 40, 50]
Print(list[ : ])
Print(list[ : 3])
Print(list[1 : 3])
Output:
[10, 20, 30, 40, 50]
[10, 20, 30]
[20, 30]

04. How are dictionary different from lists in python?


Ans:
lists Dictionary
It is an ordered collection of data it is unordered collection of key value pairs
it is mutable It is also mutable
It supports indexing It supports indexing
It can be created using list() function Can be created using dict() function
They are represented by [] They are represented by {}
Duplicate elements are allowed Duplicate elements are not allowed for
keys, but values can be duplicated

05. Explain MRO in multiple inheritance?


Ans:
• MRO(method resolution order) is the order in which the method of the class is
searched when it is being invoked.
• It refers to the order in which base classes are searched to resolve method names in
case of multiple inheritance
• It determines the order of inheritance when there are multiple base classes in
hierarchy.
Example:
Class A:
Def method(self):
Print(“ this ia method A”)
Class B(A):
Def method(self)
Print(“ this is method B”)
Class C(A):
Def method(self)
Print(“this is method C”)
Class D(B,C):
Pass
d = D()
d.method()
OUTPUT:
This is method B

06. What is the use of matplotlib library in python?


Ans:
• Matlplotlib create publication quality plots.
• Make interactive figures that can zoom, pan, update.
• Customize visual style and layout.
• Export to many file formats.
• Use a rich array of third-party packages built on matplotlib.

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

07. Explain the importance of type conversions and how it is performed?


Ans:

08. Describe the various control flow statements in python?


Ans:
Statements Syntax Example Flow control
1. If statement: If (condition): I=0
It is used to decide Statement 1 If (i>15)
whether the codes will Statement 2 Print(“10 is less than 15”)
be executed or not, if a Print(“I am not in if”)
certain condition is
true then execute the
statement is executed
otherwise not.

2. If-else If condition: i=20


statement: Statement (s) if(i<15)
If the condition is true Else: print(“i is smaller than 15”)
then the statements Statement (s) print(“I am in if block”)
present within the ‘if else:
block’ are executed; print(“I is greater than 15”)
otherwise the else print(“I am in else block”)
block are executed. print(“I am not in if and not
in else block”)
3. Nested-if: If condition 1: I=10
Nested if statements If condition 2: If(i==10):
means that an “if” Statement 1 If(i<15):
statement or “if-else” Else: Print(“I is smaller than 15”)
statement is present Statement 2 If(i<12):
inside another if or if- Else: Print(“I is smaller than 12
else block. If condition 3: too”)
Statement 3 Else:
Else: Print(“I is greater than 15”)
Statement 4
4. If-elif-else If condition: I=20
ladder: Statement 1 If(i==10):
The if-elif-else Elif (condition 2):
Print(“I is 10”)
statement is a multi- Statement 2 Elif(i==15):
way decision maker …… Print(“I is 15”)
which contains two or Else: Elif(i==20):
more branches, from Statement n Print(“I is 20”)
which any one block is Else:
executed. Print(“I is not present”)
Output: I is 20.
5. While loop: while(expression) Count = 0
It is used to execute While (count<2)
the block of codes count = count+1
repeatedly until the Print(“helloworld”)
given condition Output:
becomes false, the Helloworld
control comes out of Helloworld
the loop.

6. For loop: For iterator_var n=4


For loops are used for in sequence: for i in range(0,n):
sequential traversals Statement(s) print(i)
for example traversing Output:
a list, string or array 0
etc. 1`
2
3
4
7. Continue continue For I in range(6):
statement: If I == 3:
The continue Continue
statement is used to Print(i)
skip the rest of the Output:
statements in the 0
current loop block and 1
to continue to the next 2
iteration of the loop. 4
5

8. Break Loop For I in range(1,10):


statement: Condition: If i==5:
The break statement Break. Break
or keyword is used to Print(i)
terminate the loop. A Print(“out of the loop”)
break statement is Output:
used inside both the 1
while and for loops. 2
3
4
Out of the loop

09. Discuss built-in function used on tuple?


Ans:
Built-in-function Description Examples
all() Returns true if all elements is true all()
or if tuple is empty b=(‘a’ , ‘b’, ‘0’)
print(all(b))
output : true
any() Returns true is any element of the any()
tuple is true. If tuple is empty it c=(‘ ‘, ‘ ‘, 0)
returns false print(any(c))
output: false
Len() Returns length of the tuple or size Len()
of tuple d=(2, 3, 4, 7)
print(len(d))
output: 4
Max() Return maximum element of given Max()
tuple d=(2, 3, 4, 7)
print(max(d))
output: 7
Min() Returns minimum element of given Min()
tuple d=(2, 3, 4, 7)
print(min(d))
output: 2
Sum() Sums up the numbers in the tuple Sum()
d=(2, 3, 4, 7)
print(sum(d))
output: 16
Tuple() Convert an iterable to a tuple Tuple()
d=[2, 3, 4, 7]
print(tuple(d))
output: (2, 3, 4, 7)
Sorted() Input elements in the tuple and Sorted()
return a new sorted list d=(7, 4, 6, 5, 2, 1)
print(sorted(d))
output: (1, 2 , 4, 5, 6, 7)

10. Explain the concept of access modifiers in python?


Ans:
Encapsulation in python is achieved through the access modifiers. These access modifiers
ensures that access conditions are not breached and thus provide a great user experience in
terms of security
Types of access modifiers:
Public modifiers: by default, all attributes and methods in python are public and can be
accessed from anywhere in the code.
Private modifiers: it allows member methods and variables to be accessed only within the
class. To specify a private access modifiers for a member, we make use of the double
underscore(__) .
Protected modifier: it allows variables and functions to be accessed within the class and by
the derived class (subclass) involved protected access modifier is demonstrated by prefixing
with an underscore(_) before its name.

Program to demonstrate access modifiers:


Class person:
Def __init__ (self, name, age, sal):
Self.name= name
Self._age=age
Self.__salary=sal

Def display_details(self):
Print(“name:”, self.name)
Print(“age:”, self._age)
Print(“salary:”, self.__salary)
Person=person(“pravin”, 25, 20000)
Person.display_details()
Output:
Name: pravin
Age: 25
Salary: 20000

11. Write a python program to draw a multiline graph by reading data from CSV files and
using matplotlib?
Ans:

import pandas as pd
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.00, 3.50]


plt.rcParams["figure.autolayout"] = True

columns = ['mpg', 'displ', 'hp', 'weight']

df = pd.read_csv("auto-mpg.csv", usecols=columns)

df.plot()
plt.show()

Output:
It will produce the following output

12. Explain requests library with example?


Ans:
• The requests library is a popular python library for sending HTTP requests.
• It is designed to provide a simple and intuitive interface for making HTTP requests,
abstracting the complexities of HTTP behind a simple API.
• The basic use of requests involves sending an HTTP request to a specified URL, and
then processing the response that is received from the server.
• This can be accomplished using the requests.get method for making GET requests,
or the requests.post method POST requests
Example:
Program to demonstrate requests library to call Web API to get the gender based on
name:

Import requests
Str = input(“enter your name (I will tell your gender):”)
Url = https://api.genderized.io/?name=+str
Response = requests.get(url)
If respodnse.status_code == 200:
Data = response.json()
Print(“name:”, data1[‘name’])
Print(“gender:”, data[‘gender’])
Else:
Print(“failed to retrieve data”)
Output:
Enter your name(I will tell your gender): srikanth
Name: srikanth
Gender: male

Enter your name(I will tell your gender): bhagya


Name: bhagya
Gender: female

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

13. (a) explain string slicing with example?


Ans:
• In python string slicing is to access some part of a string or substring, we use a
method called slicing.
• The slicing operator [start : end] is used for slicing.
• This can be done by specifying an index range.
• The number of characters in the substring will always be equal to difference of
two indices start and end, i.e.,(start-end).
Example: program to demonstrate the slicing of string

Str = ‘silicon city’


Print(str[ : ])
Print(str[ : 7])
Print(str[8 : ])
Print(str[4 : 7])
Output:
Silicon city
Silicon
City
con

(b) explain command line arguments?


Ans: command line arguments:
The arguments that are given after the name of the program in the command line
shell of the operating system are known as command line arguments.
Python provides various types of arguments:
➔ Using sys.argv
➔ Using getopt module
➔ Using argparse module

a. Using sys.argv: the sys module provides functions and variables used to
manipulate different parts of the python runtime environment.
Example: program to fine the sum of three numbers using sys.argv(command
line arguments):
Import sys
Sum = 50
For i in range(1, len (sys.argv)):
Sum = sum + int (sys.argv[i])
Print(“sum:”, sum)
Output:
Sum : 50

b. Using getopt module: python provides a module named as getopt, which helps
to parse command line option and arguments. It provides a function “getopt”,
which is used for parsing the argument sequence: sys.argv.
Program to demonstrate command line arguments using getopt:
Import sys
Import getopt
def empName():
f_name = none
l_name = none
argv = sys.argv[1: ]

try:
opts, args = getopt.getopt(argv, “f:l:”)
except:
print(“invalid input”)
for opt, arg in opts:
if opt in[‘-f’]:
f_name = arg
if opt in [‘-l’ ]:
l_name = arg
print(f_name, “ “, l_name)
empName()
output:
srinivasa

c. Using argparse module: using argparse module is a better option than the above
two as it provides a lot of options such as positional arguments, default values
for arguments, help message, specifying data type of argument etc.
Program to demonstrate command line argument using argparse module:
Import argparse
Parser = argparse.ArgumentParser()
Parser.add_argument(“-o”, “—output”, help = “show output”)
Args = parser.parse_args()
If args.output:
Print(“your favorite color is: %s” %args.output)
Output:
Your favorite color is : black

14. (a) explain default arguments and variable length arguments?


Ans: DEFAULT ARGUMENTS:
A default argument is a parameter that assumes a default value if a value is
not provided in the function call for that argument.
EXAMPLE: program to demonstrate default argument:
def myfun (x, y=50)
print (“x : “, x)
print (“y: “,y)
myfun(10)
Output:
x=10
y=50

VARIABLE ARGUMENTS:
In python, we can pass a variable number of arguments to a function using two
special symbols:
*args (non-keyword arguments)
**kwargs (keyword arguments)
a. *args (non-keyword arguments)
def myfun(*args):
for arg in args:
print(arg)
myfun(‘hello’, ‘welcome’, ‘to’, ‘python’)
output:
hello
welcome
to
python

b. **kwargs (keyword arguments)


def myfun(**kwargs)
for key, value in kwargs item():
print(“%s = = %s” %(key, value))
myfun (first = ‘welcome’, mid = ‘to’, last = ‘python’)
output:
first = welcome
mid = to
last = python

(b)Explain steps for reading and writing CSV files in python?


Ans:
writing CSV files using csv.writer:
• The csv.writer object is a class from the csv module in python.’
• It provide methods for writing data into a csv file.
• It is used to write a data into a csv file in a easy and flexible way.
The csv.writer has 3 methods:
a. writerow(): writes a single row of data to the CSV file.
b. writerows(): writes multiple rows of data into the CSV file.
c. writeheader(): writes the first row of the CSV file with the file nmes.

Example: program to demonstrate writing data to CSV file using csv.writer and
writerows() method:

import csv
data = [[‘name’, ‘age’, ‘occupation’],
[‘Rana’, 35, ‘doctor’],
[‘Rama’, 32, ‘teacher’],
[‘Sita’, 28, ‘lawyer’]]
with open(‘data.csv’, ‘w’, newline= ‘ ‘) as file:
writer = csv.writer(file)
writer.writerows(data)
program to demonstrate writing data to CSV file using csv.writer and writerow()
method:
import csv
data = [[‘name’, ‘age’, ‘occupation’],
[‘Rana’, 35, ‘doctor’],
[‘Rama’, 32, ‘teacher’],
[‘Sita’, 28, ‘lawyer’]]
with open(‘data.csv’, ‘w’, newline= ‘ ‘) as file:
writer = csv.writer(file)
for row in data:
writer.writerows(data)

Reading CSV file using csv.reader:


• The csv.reader object is a class from the csv module in python that provides
methods for reading data from csv file.
• It is used to read data from a csv file in a easy and flexible way.
The csv reader has one method:
a. reader(): It returns an iterator that iterates over the rows of the csv file. each row is
returned as a list of values.

Example: program to demonstrate reading file using csv.reader:


import csv
with open(‘data.csv’, ‘r’) as file:
reader = csv.reader(file)
for row in reader:
print(row)

15. (a)explain various operations performed in list?


Ans:
1. CONCATENATE LISTS:
we can easily concatenate 2 lists using the ‘+’ operator. (concatenation is like
appending two lists).
Example:
num_list1 = [1, 3, 4, 5]
num_list2 = [5, 6, 7]
print(num_list1 + num_list2)
Output:
[1, 3, 4, 5, 5, 6, 7]

2. ADDING OR APPENDING ELEMENTS TO A LIST:


elements can be added to the list using append and insert function. using the insert
function, we can add elements at any position of a list.
Example:
sub_list = [‘python’, ‘perl’, ‘java’, ‘c++’]
#using insert
sub_list.insert(3, ’R’)
print(sub_list)
Output: [‘python’, ‘perl’, ‘java’, ‘R’, ‘c++’]
#using append
sub_list.append(‘Django’)
print(sub_list)
Output: [‘python’, ‘perl’, ‘java’, ‘c++’, ‘Django’]

3. UPDATE ELEMENTS OF A LIST:


As lists are changeable, we can update the elements of the lists using the index
of the elements.

Example:
mix-list = [1, ‘jerry’, ‘science’, 78.5, true]
mix_list[2] = ‘computer’
print(mix_list)
Output:
[1, ‘jerry’, ‘computer’, 79.5, true]

4. DELETE ELEMENTS OF A LIST:


we can easily delete the elements of the list using the remove function.
Example:
sub_list = [‘python’, ‘perl’, ‘java’, ‘c++’]
sub_list.remove(‘java’)
print(sub_list)
Output: [‘python’, ‘perl’, ‘c++’]

5. POP ELEMENTS OF A LIST:


the pop function is used to remove or pop out the last element from the list.
Example:
num_list = [1, 2, 3, 4, 6]
num_list.pop()
print(num_list)
Output: [1, 2, 3, 4]

(b)Discuss the 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.

16. (a) How polymorphism is achieved in python?


Ans: Polymorphism: it is refers to the ability of an object or operator or function to take
on multiple forms.
there are 4 ways to achieve polymorphism:
1. Method overloading: It means a class containing multiple methods with the same
name but may have different parameters.
Example:
class Rectangle:
def __init__ (self, width=0, height=0):
self.width=width
self.height=height
def area(self):
return self.width * self.height
rect1 = Rectangle()
rect2 = Rectangle(10, 20)
print(rect1.area())
print(rect2.area())
output:
0
200

2. Method overriding: it is the method that allows us to change the implementation of


function in a child class that is defined in the parent class.
Example:
class camera:
def shoot(self):
print(“shoot with a standard camera”)
class SLRcamera(camera):
def shoot(self):
print(“shoot with SLR camera”)
standard_camera = camera()
slr_camera = SLRcamera()
standard_camera.shoot()
slr_camera.shoot()
Output:
shoot with a standard camera
shoot with a SLR camera

3. Method operator overloading: it provides extended meaning beyond their


predefined operational meaning such as ‘+’, ‘-‘, ‘*’ etc operator.
Example:
class point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Point(x, y)
def __str__(self):
return f: ({self.x}, {self.y})”
p1 = Point(1, 2)
print(“p1=”, p1)
p2 = Point(3, 4)
print(“p1=”,p2)
p3 = p1 + p2
print(“ Addition of p1 and p2 =”, p3)
Output:
p1 = (1, 2)
p1 = (3, 4)
addition of p1 and p2 = (4, 6)

4. Duck typing: it is the concept of dynamic programming language like python where
the type of an object is determined by its behavior rather than its class definition. in
other words, it is based on the idea that “if it walks and quake like a duck , it is a
duck”.
Example:
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 steps to read and write the binary files in python?
Ans: binary files: these are the files which stores information in the same format in
which the information is held in memory are called binary files.
there are two types of binary files:

1. write binary file: use the ‘wb’ (write binary) mode in the open() function to write a
binary file.
To open a function (<file object> = open (file name> or <file path>, <file mode>)

2. read binary file: : use the ‘rb’ (read binary) mode in the open() function to read a
binary file.

example: program to read and write a binary data.

binary_data = b”\x01\x02\x03\x04”
with open (“binary_file.dat”, “wb”) as file:
file.write (binary_data)
with open (“binary_file.dat”, “rb”) as file:
read_data = file.read()
print(“read data:”, read_data)
OUTPUT:
binary data: b‘\x01\x02\x03\x04’

17. (a) Explain the steps to create the class and objects in python?
Ans:

(b) Discuss the different types of files in python?


Ans: A file is named location on disk to store related information. It is used to store data
permanently in a non-volatile memory.
There are two types of file:
Text file:
• Text file store the data in the form of characters.
• Text file are used to store characters or string.
• They contain human-readable text and are encoded using either ASCII or
Unicode character sets.
Example:
Tabular data, documents, configuration, web standards.

Binary file:
• Binary file stores entire data in the form of bytes.
• Binary files can be used to store text, image, audio, and video.
• They contain non-human-readable binary data. it is stored in specific format
and its interpretation depends on the type of binary file
Example:
Document files, Executable files, Image files, Audio file, Video files, Database
files, Archive files.

18. (a) Explain rolling dice . Write a program to illustrate the same?
Ans:
ROLLING DICE: In this article, we will create a classic rolling dice simulator with the help of
basic Python knowledge. Here we will be using the random module since we randomize the
dice simulator for random outputs.
Function used:
1) random.randint(): This function generates a random number in the given range. Below is
the implementation.

import random

x = "y"
while x == "y":
no = random.randint(1,6)
if no == 1:
print("[-----]")
print("[ ]")
print("[ 0 ]")
print("[ ]")
print("[-----]")
if no == 2:
print("[-----]")
print("[ 0 ]")
print("[ ]")
print("[ 0 ]")
print("[-----]")
if no == 3:
print("[-----]")
print("[ ]")
print("[0 0 0]")
print("[ ]")
print("[-----]")
if no == 4:
print("[-----]")
print("[0 0]")
print("[ ]")
print("[0 0]")
print("[-----]")
if no == 5:
print("[-----]")
print("[0 0]")
print("[ 0 ]")
print("[0 0]")
print("[-----]")
if no == 6:
print("[-----]")
print("[0 0 0]")
print("[ ]")
print("[0 0 0]")
print("[-----]")

x=input("press y to roll again and n to exit:")


print("\n")

Output:
(b) Write a program to read data from GitHub and use the data to visualize using plotly?
Ans:

You might also like