Python Model Paper-02
Python Model Paper-02
PART- A
writing code. One can write Python code in procedural, object oriented, functional or
imperative manner.
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
write multi-line strings or display them in the desired way. Example: Here geekforgeeks is
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
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.
Method Resolution Order(MRO) it denotes the way a programming language resolves a method
Example:
class A:
def rk(self):
class B(A):
def rk(self):
r = B()
r.rk()
Output:
In class B
PART-B
Python defines type conversion functions to directly convert one data type to another which is
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
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:
Y is of type: <class
‘float’> 20.6
Z is of type: <class
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
Example:
# initializing string
S = “10010”
2 C = int(s,2)
Print ©
E = float(s)
Print (e)
Output:
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
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.
Example:
I = 10
If (I > 15):
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
Syntax:
If (condition):
if # condition is true
Else:
if # condition is false
Example:
I = 20
If (I < 15):
Print(“I’m in if Block”)
Else:
Block”)
Output:
I is greater than
15 I’m 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
Syntax:
If (condition1):
true If (condition2):
#!/usr/bin/python
I = 10
If (I == 10):
# First if statement
If (I < 15):
# it is true
If (I < 12):
Else:
I is smaller than 15
I is smaller than 12
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
Syntax:
If (condition):
Statement
Elif (condition):
Statement
Else:
Statement
FlowChart of Python if else elif statements
#!/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
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.
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 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
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
Example –
Import requests
R=requests.get(‘https://api.github.com/users/naveenkrnl’)
Print®
Print(r.content)
Python request.py
Output:
PART-C
Answer any 4 questions each question carries 8 marks
Python slicing is about obtaining a sub-string from the given string by slicing it respectively
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
# string slicing
# String slicing
String = ‘ASTRING’
S1 = slice(3)
S2 = slice(1, 5, 2)
Print(String[s2])
Print(String[s3])
Output:
String slicing
AST
SR
GITA
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
Example: Let’s suppose there is a Python script for adding two numbers and the numbers
Import sys
# total arguments
N = len(sys.argv)
end = “ “)
Print(sys.argv[i], end = “
“)
# Addition of
numbers Sum = 0
# Using argparse
n):
Sum += int(sys.argv[i])
Print(“\n\nResult:”, Sum)
Output
(b) explain the steps to reading and writing CSV files 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(=)
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
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
Syntax:
Example:
Consider the below CSV file –
Import csv
csvFile = csv.reader(file)
Print(lines)
Output:
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:
Example:
# writing to CSV
Import csv
# field names
Filename = “university_records.csv”
Csvwriter = csv.writer(csvfile)
Csvwriter.writerow(fields)
Csvwriter.writerows(rows)
Output:
15.(a)Explain the various operations that can be performed in the lists in python
1 append() Used for appending and adding elements to the end of the List.
3 clear() This method is used for removing all items from the list.
5 extend() Adds each element of the iterable to the end of the List
dictionary
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
dictionary 16.(a)Discuss the steps to read and write binary files in Python.
files that can be handled in python, normal text files and binary files (written in binary
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
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,
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
In this article, we will be focusing on opening, closing, reading, and writing data in a text
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
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
Writing to a file
file. File_object.write(str1)
Writelines() : For a list of string elements, each string is inserted in the text file.Used to insert
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()
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-
Create Object. Now we can use the class named MyClass to create
Delete Objects.
Binary File
1. Text File
Eg: abc.txt
2. Binary File
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
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
F = open(filename, mode)
To write data into file. If any data is already present in the file, it would be deleted and the
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
R+
To read and write data into the file. The previous data in the file will not be deleted.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
Note : All the above modes are applicable for text files. If the above modes suffixed with ‘b’
Eg: rb,wb,ab,r+b,w+b,a+b,xb
F = open(“abc.txt”,”w”)
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
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
Function used:
1) Random.randint(): This function generates a random number in the given range. Below is
the implementation.
Example 1: Dice
X = “y”
While x == “y”:
# Generates a random
(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(“[
]”)
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
instance Print(fig)
Output:
Plotly.plotly acts as the interface between the local machine and Plotly. It contains functions that
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
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