0% found this document useful (0 votes)
87 views34 pages

Python Model Paper-02

This document contains a model question paper for a Python exam. It includes questions about Python fundamentals like data types, control flow, functions and libraries. The questions are divided into three parts with questions having different marks based on difficulty. Key concepts covered include lists, dictionaries, classes, inheritance and modules.

Uploaded by

Pavithra
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)
87 views34 pages

Python Model Paper-02

This document contains a model question paper for a Python exam. It includes questions about Python fundamentals like data types, control flow, functions and libraries. The questions are divided into three parts with questions having different marks based on difficulty. Key concepts covered include lists, dictionaries, classes, inheritance and modules.

Uploaded by

Pavithra
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/ 34

Model question paper 2

PART- A

Answer any four questions each question carries 2 marks

1. Why python is called multi-paradigm programming language?

Python is a multi-paradigm programming language. Meaning it supports different styles of

writing code. One can write Python code in procedural, object oriented, functional or

imperative manner.

2. What is keyword and literals in python programming language? Give example.

Keywords :are some predefined and reserved words in python that have special meanings.

Keywords are used to define the syntax of the coding. The keyword cannot be used as an

identifier, function, and variable name. All the keywords in python are written in lower

case except True and False

Literals:A string literal can be created by writing a text(a group of Characters )

surrounded by a single(”), double(“”), or triple quotes. By using triple quotes we can

write multi-line strings or display them in the desired way. Example: Here geekforgeeks is

a string literal that is assigned to a variable(s).

3. Explain the concept of indexing and slicing in lists

Indexing: means referring to an element of an iterable by its position within the iterable. Each of

a string’s characters corresponds to an index number and each character can be accessed using

its index number.

Slicing: in Python is a feature that enables accessing parts of the sequence. In slicing a string, we

create a substring, which is essentially a string that exists within another string. We use slicing

when we require a part of the string and not the complete string.
4. How are dictionaries different from lists in Python

Both of these are tools used in the Python language, but there is a crucial difference between List

and Dictionary in Python. A list refers to a collection of various index value pairs like that in the

case of an array in C++. A dictionary refers to a hashed structure of various pairs of keys and

values.

5. Explain MRO in multiple inheritance

Method Resolution Order(MRO) it denotes the way a programming language resolves a method

or attribute. Python supports classes inheriting from other classes.

Example:

# Python program showing

# how MRO works

class A:

def rk(self):

print(" In class A")

class B(A):

def rk(self):

print(" In class B")

r = B()

r.rk()

Output:

In class B

6. what is the use of matplotlib library?

Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy

library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like


interface. There are various plots which can be used in Pyplot are Line Plot, Contour,

Histogram, Scatter, 3D Plot, etc.

PART-B

Answer any 4 questions.each question carries 5 marks

7. Explain the importance of type conversions in python and how it can be be

performed Type Conversion in Python

Python defines type conversion functions to directly convert one data type to another which is

useful in day-to-day and competitive programming. This article is aimed at providing

information about certain conversion functions.

There are two types of Type Conversion in Python:

Implicit Type Conversion

Explicit Type Conversion


Implicit Type Conversion

In Implicit type conversion of data types in Python, the Python interpreter automatically converts

one data type to another without any user involvement. To get a more clear view of the topic see

the below examples.

Example:

X = 10

Print(“x is of type:”,type(x))

Y = 10.6

Print(“y is of type:”,type(y))

Z=x+y

Print(z)

Print(“z is of type:”,type(z))

Output:

X is of type: <class ‘int’>

Y is of type: <class

‘float’> 20.6

Z is of type: <class

‘float’> Explicit Type

Conversion

In Explicit Type Conversion in Python, the data type is manually changed by the user as per their

requirement. With explicit type conversion, there is a risk of data loss since we are forcing an

expression to be changed in some specific data type.

Example:

# Python code to demonstrate Type conversion


# using int(), float()

# initializing string

S = “10010”

# printing string converting to int base

2 C = int(s,2)

Print (“After converting to integer base 2 : “, end=””)

Print ©

# printing string converting to float

E = float(s)

Print (“After converting to float : “, end=””)

Print (e)

Output:

After converting to integer base 2 : 18

After converting to float : 10010.0

8. Describe the various control flow statements in

Python If statement

If statement is the most simple decision-making statement. It is used to decide whether a certain

statement or block of statements will be executed or not i.e if a certain condition is true then a

block of statement is executed otherwise not.

Syntax:

If condition:

# Statements to execute

if # condition is true
Here, the condition after evaluation will be either true or false. If the statement accepts boolean

values – if the value is true then it will execute the block of statements below it otherwise not.

We can use condition with bracket ‘(‘ ‘)’ also.

Flowchart of Python if statement

Example:

# python program to illustrate If statement

I = 10

If (I > 15):

Print(“10 is less than 15”)

Print(“I am Not in if”)

Output:

I am Not in if

If-else
The if statement alone tells us that if a condition is true it will execute a block of statements and

if the condition is false it won’t. But what if we want to do something else if the condition is

false. Here comes the else statement. We can use the else statement with if statement to execute

a block of code when the condition is false.

Syntax:

If (condition):

# Executes this block

if # condition is true

Else:

# Executes this block

if # condition is false

FlowChart of Python if-else statement

Example:

# python program to illustrate If else statement


#!/usr/bin/python

I = 20

If (I < 15):

Print(“I is smaller than 15”)

Print(“I’m in if Block”)

Else:

Print(“I is greater than

15”) Print(“I’m in else

Block”)

Print(“I’m not in if and not in else Block”)

Output:

I is greater than

15 I’m in else

Block

I’m not in if and not in else Block

Nested-if

A nested if is an if statement that is the target of another if statement. Nested if statements mean

an if statement inside another if statement. Yes, Python allows us to nest if statements within if

statements. i.e, we can place an if statement inside another if statement.

Syntax:

If (condition1):

# Executes when condition1 is

true If (condition2):

# Executes when condition2 is true


# if Block is end here

# if Block is end here

Flowchart of Python Nested if Statement

# python program to illustrate nested If statement

#!/usr/bin/python

I = 10

If (I == 10):

# First if statement

If (I < 15):

Print(“I is smaller than

15”) # Nested – if statement

# Will only be executed if statement above

# it is true

If (I < 12):

Print(“I is smaller than 12 too”)

Else:

Print(“I is greater than 15”)


Output:

I is smaller than 15

I is smaller than 12

too If-elif-else ladder

Here, a user can decide among multiple options. The if statements are executed from the top

down. As soon as one of the conditions controlling the if is true, the statement associated with

that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then

the final else statement will be executed.

Syntax:

If (condition):

Statement

Elif (condition):

Statement

Else:

Statement
FlowChart of Python if else elif statements

# Python program to illustrate if-elif-else ladder

#!/usr/bin/python

I = 20

If (I == 10):

Print(“I is 10”)

Elif (I == 15):

Print(“I is 15”)

Elif (I == 20):

Print(“I is 20”)

Else:

Print(“I is not

present”) Output:

I is 20

9. Discuss the built-in functions used in python.


10. Explain the concept of access modifiers in

Python Access Modifiers in Python :

Public Access Modifier

Protected Access Modifier

Private Access Modifier

Public Access Modifier:

The members of a class that are declared public are easily accessible from any part of the

program. All data members and member functions of a class are public by default.

Protected Access Modifier:

The members of a class that are declared protected are only accessible to a class derived from it.

Data members of a class are declared protected by adding a single underscore ‘_’ symbol before

the data member of that class.

Private Access Modifier:

The members of a class that are declared private are accessible within the class only, private

access modifier is the most secure access modifier. Data members of a class are declared private

by adding a double underscore ‘ ’ symbol before the data member of that class.

11. Write Python program to draw a multiline graph By reading data from CSV files and using

matplotlib
12. Explain requests library with an

example Python Requests Tutorial

Requests library is one of the integral part of Python for making HTTP requests to a specified

URL. Whether it be REST APIs or Web Scraping, requests is must to be learned for proceeding
further with these technologies. When one makes a request to a URI, it returns a response.

Python requests provides inbuilt functionalities for managing both the request and

response. Syntax –Requests.get(url, params={key: value}, args)

Example –

Let’s try making a request to github’s APIs for example purposes.

Import requests

# Making a GET request

R=requests.get(‘https://api.github.com/users/naveenkrnl’)

# check status code for response received

# success code – 200

Print®

# print content of request

Print(r.content)

Save this file as request.py and through terminal run,

Python request.py

Output:

PART-C
Answer any 4 questions each question carries 8 marks

13.(a) Explain string slicing with example

(b) Explain command line arguments

(a)String Slicing in Python

Python slicing is about obtaining a sub-string from the given string by slicing it respectively

from start to end.

How String slicing in Python works

For understanding slicing we will use different methods, here we will cover 2 methods of string

slicing, the one is using the in-build slice() method and another using the [:] array slice. String

slicing in Python is about obtaining a sub-string from the given string by slicing it respectively

from start to end.

Python slicing can be done in two ways:

Using a slice() method

Using array slicing [ : : ] method

# Python program to demonstrate

# string slicing

# String slicing

String = ‘ASTRING’

# Using slice constructor

S1 = slice(3)

S2 = slice(1, 5, 2)

S3 = slice(-1, -12, -2)

Print(& quot String slicing & quot)


Print(String[s1])

Print(String[s2])

Print(String[s3])

Output:

String slicing

AST

SR

GITA

(b) Command Line Arguments in Python

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 ways of

dealing with these types of arguments. The three most common are:

Using sys.argv

Using getopt module

Using argparse module

Example: Let’s suppose there is a Python script for adding two numbers and the numbers

are passed as command-line arguments.

# Python program to demonstrate

# command line arguments

Import sys

# total arguments

N = len(sys.argv)

Print(“Total arguments passed:”, n)


# Arguments passed

Print(“\nName of Python script:”,

sys.argv[0] Print(“\nArguments passed:”,

end = “ “)

For I in range(1, n):

Print(sys.argv[i], end = “

“)

# Addition of

numbers Sum = 0

# Using argparse

module For I in range(1,

n):

Sum += int(sys.argv[i])

Print(“\n\nResult:”, Sum)

Output

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

(b) explain the steps to reading and writing CSV files in Python

(a) Default arguments in Python

Python allows function arguments to have default values. If the function is called without the
argument, the argument gets its default value.
Default Arguments:

Python has a different way of representing syntax and default values for function arguments.

Default values indicate that the function argument will take that value if no argument value is

passed during the function call. The default value is assigned by using the assignment(=)

operator of the form keywordname=value.

Let’s understand this through a function student. The function student contains 3-arguments out

of which 2 arguments are assigned with default values. So, the function student accepts one

required argument (firstname), and rest two arguments are optional.

Def student(firstname, lastname =’Mark’, standard =’Fifth’):

Print(firstname, lastname, ‘studies in’, standard, ‘Standard’).

Avariable-length argument is a feature that allows a function to receive any number of

arguments. There are situations where a function handles a variable number of

arguments according to requirements, such as: Sum of given numbers

(b) Reading from CSV file

Python contains a module called csv for the handling of CSV files. The reader class from the

module is used for reading data from a CSV file. At first, the CSV file is opened using the

open() method in ‘r’ mode(specifies read mode while opening a file) which returns the file object

then it is read by using the reader() method of CSV module that returns the reader object that

iterates throughout the lines in the specified CSV document.

Syntax:

Csv.reader(csvfile, dialect=’excel’, **fmtparams

Example:
Consider the below CSV file –

Import csv

# opening the CSV file

With open(‘Giants.csv’, mode =’r’)as

file: # reading the CSV file

csvFile = csv.reader(file)

# displaying the contents of the CSV file

For lines in csvFile:

Print(lines)

Output:

[[‘Steve’, 13, ‘A’],

[‘John’, 14, ‘F’],

[‘Nancy’, 14, ‘C’],

[‘Ravi’, 13, ‘B’]]


Writing to CSV file

Csv.writer class is used to insert data to the CSV file. This class returns a writer object which is

responsible for converting the user’s data into a delimited string. A CSV file object should be

opened with newline=” otherwise, newline characters inside the quoted fields will not be

interpreted correctly.

Syntax:

Csv.writer(csvfile, dialect=’excel’, **fmtpar

Example:

# Python program to demonstrate

# writing to CSV

Import csv

# field names

Fields = [‘Name’, ‘Branch’, ‘Year’, ‘CGPA’]

# data rows of csv file

Rows = [ [‘Nikhil’, ‘COE’, ‘2’, ‘9.0’],

[‘Sanchit’, ‘COE’, ‘2’, ‘9.1’],

[‘Aditya’, ‘IT’, ‘2’, ‘9.3’],

[‘Sagar’, ‘SE’, ‘1’, ‘9.5’],

[‘Prateek’, ‘MCE’, ‘3’, ‘7.8’],

[‘Sahil’, ‘EP’, ‘2’, ‘9.1’]]

# name of csv file

Filename = “university_records.csv”

# writing to csv file


With open(filename, ‘w’) as csvfile:

# creating a csv writer object

Csvwriter = csv.writer(csvfile)

# writing the fields

Csvwriter.writerow(fields)

# writing the data rows

Csvwriter.writerows(rows)

Output:

15.(a)Explain the various operations that can be performed in the lists in python

(b) discuss the built in function used on dictionaries in python

(a) S.no Method Description

1 append() Used for appending and adding elements to the end of the List.

2 copy() It returns a shallow copy of a list

3 clear() This method is used for removing all items from the list.

4 count() This methods count the elements

5 extend() Adds each element of the iterable to the end of the List

6 index() Returns the lowest index where the element appears.

7 insert() Inserts a given element at a given index in a list.


8 pop() Removes and returns the last value from the List or the given index value.

9 remove() Removes a given object from the List.

10 reverse() Reverses objects of the List in place.

11 sort() Sort a List in ascending, descending, or user-defined order

12 max() Calculates maximum of all the elements of List

(b) Functions Name Description

Clear() Removes all items from the dictionary

Copy() Returns a shallow copy of the

dictionary

Fromkeys() Creates a dictionary from the given

sequence Get() Returns the value for the given key

Items() Return the list with all dictionary keys with values

Keys() Returns a view object that displays a list of all the keys in the dictionary in order of

insertion

Pop() Returns and removes the element with the given key

Popitem() Returns and removes the key-value pair from the dictionary

Setdefault() Returns the value of a key if the key is in the dictionary else inserts the key with

a value to the dictionary

Update() Updates the dictionary with the elements from another

dictionary Values() Returns a list of all the values available in a given

dictionary 16.(a)Discuss the steps to read and write binary files in Python.

(b)How polymorphism is achieved in object oriented programming

(a) Reading and Writing to text files in Python


Python provides inbuilt functions for creating, writing, and reading files. There are two types of

files that can be handled in python, normal text files and binary files (written in binary

language, 0s, and 1s).

Text files: In this type of file, Each line of text is terminated with a special character called EOL

(End of Line), which is the new line character (‘\n’) in python by default.

Binary files: In this type of file, there is no terminator for a line, and the data is stored after

converting it into machine-understandable binary language.

Reading and Writing to text files in Python

Python provides inbuilt functions for creating, writing, and reading files. There are two types of

files that can be handled in python, normal text files and binary files (written in binary language,

0s, and 1s).

Text files: In this type of file, Each line of text is terminated with a special character called EOL

(End of Line), which is the new line character (‘\n’) in python by default.

Binary files: In this type of file, there is no terminator for a line, and the data is stored after

converting it into machine-understandable binary language.

In this article, we will be focusing on opening, closing, reading, and writing data in a text

file. File Access Modes

Access modes govern the type of operations possible in the opened file. It refers to how the file

will be used once its opened. These modes also define the location of the File Handle in the file.

File handle is like a cursor, which defines from where the data has to be read or written in the

file. There are 6 access modes in python.


Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file.

If the file does not exists, raises the I/O error. This is also the default mode in which a file is

opened.

Read and Write (‘r+’): Open the file for reading and writing. The handle is positioned at the

beginning of the file. Raises I/O error if the file does not exist.

Write Only (‘w’) : Open the file for writing. For the existing files, the data is truncated and over-

written. The handle is positioned at the beginning of the file. Creates the file if the file does not

exist.

Write and Read (‘w+’) : Open the file for reading and writing. For an existing file, data

is truncated and over-written. The handle is positioned at the beginning of the file.

Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The handle is

positioned at the end of the file. The data being written will be inserted at the end, after the

existing data.

Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not

exist. The handle is positioned at the end of the file. The data being written will be inserted at the

end, after the existing data.

Writing to a file

There are two ways to write in a file.

Write() : Inserts the string str1 in a single line in the text

file. File_object.write(str1)

Writelines() : For a list of string elements, each string is inserted in the text file.Used to insert

multiple strings at a single time.

File_object.writelines(L) for L = [str1, str2, str3]


Reading from a file

There are three ways to read data from a text file.

Read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the

entire file.

File_object.read([n])

Readline() : Reads a line of the file and returns in form of a string.For specified n, reads at most

n bytes. However, does not reads more than one line, even if n exceeds the length of the line.

File_object.readline([n])

Readlines() : Reads all the lines and return them as each line a string element in a list.

File_object.readlines()

(b) With Method Overloading, static polymorphism is achieved in Object-Oriented

Programming languages that allow the programmer to implement various methods. The names

they use can be the same, but their parameters are different. In OOPS, you can attain compile-

time polymorphism using method overloading

17.(a) Explain the steps to create classes and objects in Python

(b) Discuss the different types of files in Python

(a) Python Classes and Objects

Create a Class. To create a class, use the keyword class :

Create Object. Now we can use the class named MyClass to create

objects: The self Parameter.

Modify Object Properties.


Delete Object Properties.

Delete Objects.

(b) Types of Files in

Python Text File

Binary File

1. Text File

Text file store the data in the form of characters.

Text file are used to store characters or strings.

Usually we can use text files to store character data

Eg: abc.txt

2. Binary File

Binary file store entire data in the form of bytes.

Binary file can be used to store text, image, audio and video.

Usually we can use binary files to store binary data like images,video files, audio files etc

Opening a File

Before performing any operation (like read or write) on the file,first we have to open that

file.For this we should use Python’s inbuilt function open()

But at the time of open, we have to specify mode,which represents the purpose of opening file.

We should use open() function to open a file. This function accepts ‘filename’ and ‘open

mode’ in which to open the file.

File handler = open(“file name”, “open mode”, “buffering”)

F = open(filename, mode)

The File Opening Mode


W

To write data into file. If any data is already present in the file, it would be deleted and the

present data will be stored.

Open an existing file for write operation. If the file already contains some data then it will be

overridden. If the specified file is not already available then this mode will create that file.

To read the data form the file. The file pointer is positioned at the beginning of the file.

Open an existing file for read operation. The file pointer is positioned at the beginning of the

file.If the specified file does not exist then we will get FileNotFoundError.This is default mode.

To append data to the file. Appending means adding at the end of existing data. The file

pointer is placed at the end of the file. If the file does not exist, it will create new for writing

data.

Open an existing file for append operation. It won’t override existing data.If the specified file

is not already avaialble then this mode will create a new file.

W+

To write and read data a file. The previous data in the file will be

deleted. To write and read data. It will override existing data.

R+

To read and write data into the file. The previous data in the file will not be deleted.The file

pointer is placed at the beginning of the file.

A+

To append and read data from the file.It wont override existing data.
To append and read of a file. The file pointer will be at the end of the file if the file exists. If the

file does not exist, it creates a new file for reading and writing.

To open a file in exclusive creation mode for write operation. If the file already exists then we

will get FileExistsError.

Note : All the above modes are applicable for text files. If the above modes suffixed with ‘b’

then these represents for binary files.

Eg: rb,wb,ab,r+b,w+b,a+b,xb

F = open(“abc.txt”,”w”)

We are opening abc.txt file for writing data.

18.(a) Explain the rolling dice with plotly. write a program to illustrate the same

(b) Write a program to read data from GitHub And use data to visualize Using ploty

(a) Dice Rolling Simulator using Python-random

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.

Example 1: Dice

Simulator Import random

X = “y”
While x == “y”:

# Generates a random

number # between 1 and 6

(including

# both 1 and 6)

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”)
(b) Using Plotly for Interactive Data Visualization in Python

Plotly is an open-source module of Python which is used for data visualization and supports

various graphs like line charts, scatter plots, bar charts, histograms, area plot, etc. In this article,

we will see how to plot a basic chart with plotly and also how to make a plot interactive. But

before starting you might be wondering why there is a need to learn plotly, so let’s have a look

at it.

Example:

Import plotly.express as px

# Creating the Figure instance

Fig = px.line(x=[1, 2], y=[3,

4]) # printing the figure

instance Print(fig)

Output:

Plotly figure class


Overview of Plotly Package Structure

In Plotly, there are three main modules –

Plotly.plotly acts as the interface between the local machine and Plotly. It contains functions that

require a response from Plotly’s server.

Plotly.graph_objects module contains the objects (Figure, layout, data, and the definition of the

plots like scatter plot, line chart) that are responsible for creating the plots. The Figure can be

represented either as dict or instances of plotly.graph_objects.Figure and these are serialized as

JSON before it gets passed to plotly.js. Figures are represented as trees where the root node has

three top layer attributes – data, layout, and frames and the named nodes called ‘attributes’.

Note: plotly.express module can create the entire Figure at once. It uses the graph_objects

internally and returns the graph_objects.Figure instance.

You might also like