Python Solved Model QP-1
Python Solved Model QP-1
USN
First/Second Semester B.E. Degree Examination
Introduction to Python Programming
TIME: 03 Hours Max. Marks: 100
Note: 01. Answer any FIVE full questions, choosing at least ONE question from each MODULE.
Bloom’s
Module -1 Taxonomy Marks
.IN
Level
Q.01 a What is an arithmetic expression? . What is the output of this statement? CO2-L3 6
‘hello world’ + 100 + ’how are you’ explain the reason if the statement
produces an error.
C
An arithmetic expression is a combination of numbers, operators, and
parentheses that represents a mathematical calculation. The operators can be
N
addition (+), subtraction (-), multiplication (*), division (/), exponentiation (^),
or any other valid arithmetic operator.
SY
The above statement will produce an error because you cannot concatenate a
string and an integer without converting the integer to a string first.
VT
1. The string 'hello world' is concatenated with the integer 100, which causes a
TypeError because you can only concatenate strings together.
1. 1.
2. import module_name: This statement imports the entire module and allows
you to use its functions, classes, and variables with the module_name. prefix.
For example:
import math
print(math.pi)
2. 2.
Page 01 of 02
22PLC15B/25B
3. from module_name import function_name : This statement imports a
specific function from a module and allows you to use it without the
module_name. prefix. For example:
3. 3.
4. import module_name as alias_name: This statement imports a module and
gives it an alias name to use in the program. For example:
import numpy as np
arr = np.array([1, 2, 3])
4. 4.
5. from module_name import *: This statement imports all functions, classes,
and variables from a module into the program's namespace. However, this
method is generally discouraged because it can lead to naming conflicts and
make the code harder to read and understand.
.IN
c What is the lambda function? Explain with an example of addition of two CO2 – L1 7
numbers.
In Python, a lambda function is a small anonymous function that can take any
number of arguments, but can only have one expression. Lambda functions are
useful when you need a simple function for a short period of time and do not
C
want to define a full function using the def statement. Lambda functions are
defined using the keyword lambda , followed by the function's arguments and
N
expression.
SY
addition = lambda x, y: x + y
print(addition(2, 3))
U
OR
Q.02 a What is a flow control statement?. Discuss if and if else statements with CO1 - L1 7
flow chart.
Page 02 of 02
22PLC15B/25B
EXAMPLE:
n = 10
if n % 2 == 0:
print("n is an even number")
if-else: The if-else statement evaluates the condition and will execute the
body of if if the test condition is True, but if the condition is False, then
the body of else is executed.
.IN
EXAMPLE:
n=5
if n % 2 == 0:
print("n is even")
else: C
N
print("n is odd")
SY
b Write a python program to add n numbers accepted from the user. CO2 – L3 7
for i in range(n):
num = float(input("Enter a number: "))
total += num
VT
OUTPUT:
How many numbers do you want to add? 5
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
The sum of the entered numbers is: 15.0
c How can you prevent a python program from crashing? discuss different CO2 – L2 6
ways to avoid crashing.
There are several ways to prevent a Python program from crashing. Here are
some of them:
Input validation: One common cause of program crashes is invalid input.
You can prevent this by validating user input before processing it.
Error handling: Python has built-in error handling mechanisms, such as try-
except blocks, which can catch and handle errors that may cause a program to
crash.
Memory management: You can prevent these types of errors by managing
Page 03 of 02
22PLC15B/25B
memory carefully, such as releasing unused memory or avoiding infinite
loops.
Testing and debugging: Finally, one of the best ways to prevent program
crashes is to thoroughly test and debug your code. This includes writing unit
tests to validate your code and using debugging tools, such as print
statements or a debugger, to identify and fix issues before they cause a crash.
Module-2
Q. 03 a Discuss list and dictionary data structure with example for each. CO2 – L1 6
.IN
C
N
b write a python program to accept n numbers and store them in a list. Then CO2 – L2 6
SY
numbers = []
for i in range(n):
VT
OUTPUT:
How many numbers do you want to enter? 5
Enter a number: 3
Enter a number: 4
Enter a number: 5
Enter a number: 2
Enter a number: 6
The even numbers in the list are: [4, 2, 6]
c For a=[‘hello’, ‘how’, [1,2,3], [[10,20,30]]] what is the output of following CO2 – L3 8
statement (i) print( a[ : : ] ) (ii) print(a[-3][0]) (iii) print(a[2][ : -1])
(iv) print(a[0][ : : -1])
Page 04 of 02
22PLC15B/25B
For the given list a=[‘hello’, ‘how’, [1,2,3], [[10,20,30]]], the output of
the following statements will be:
(i) print(a[::]) will print the entire list a as it is. The output will be:
(ii) print(a[-3][0]) will print the first element of the third element of the list a .
The third element of a is the list [1, 2, 3], and the first element of that list is 1.
The output will be:
1
(iii) print(a[2][:-1]) will print all the elements of the third element of the list a ,
except the last element. The third element of a is the list [1, 2, 3], and all its
elements except the last element is [1, 2]. The output will be:
[1, 2]
(iv) print(a[0][::-1]) will print the first element of the list a in reverse order.
The first element of a is the string 'hello', and its reverse order is 'olleh'. The
output will be:
.IN
'olleh'
OR
Q.04 a
C
write a python program to read dictionary data and delete any given key
entry in the dictionary.
CO3 – L23 7
N
# Read the dictionary from the user
n = int(input("How many key-value pairs do you want to enter? "))
SY
d = {}
for i in range(n):
key = input("Enter a key: ")
U
Here are some of the commonly used clipboard functions in Python that can be
used in wiki markup:
1. pyperclip.copy(text) - This function copies the given text to the clipboard. The
text argument is a string that contains the text to be copied.
2. pyperclip.paste() - This function retrieves the current contents of the clipboard
and returns it as a string.
3. pyperclip.cut() - This function cuts the current selection from the clipboard and
returns it as a string.
4. pyperclip.clear() - This function clears the contents of the clipboard.
c Using string slicing operation write python program to reverse each word CO2 – L3 8
in a given string (eg: input: “hello how are you”, output: “olleh woh era
uoy”)
.IN
# Reverse each word of a Sentence
# Function to Reverse words
def reverseword(s):
w = s.split(" ")
C
# Splitting the Sentence into list of words.
# reversing each word and creating a new list of words
N
# apply List Comprehension Technique
nw = [i[::-1] for i in w]
# Join the new list of words to for a new Sentence
SY
ns = " ".join(nw)
return ns
# Driver's Code
s = input("ENTER A SENTENCE PROPERLY ::")
print(reverseword(s))
U
OUTPUT:
ENTER A SENTENCE PROPERLY ::
VT
In Python, the os module provides several functions for working with the file
system. These functions allow you to manipulate file paths, check if files or
directories exist, create new directories, and perform other operations on the file
system. Here are some of the commonly used paths of file system in Python:
1. Absolute path: An absolute path is the full path of a file or directory, starting
from the root directory of the file system. In Unix-based systems, the root
directory is typically denoted by a forward slash (/), while in Windows systems, it
is denoted by a backslash (). For example, "/home/user/myfile.txt" is an absolute
path on a Unix system, while "C:\Users\User\Documents\myfile.txt" is an
absolute path on a Windows system.
2.
3. Relative path: A relative path is a path that is relative to the current working
directory of the program.
4. For example, "mydir/myfile.txt" is a relative path that specifies a file called
"myfile.txt" located in a directory called "mydir" that is located in the current
working directory.
5. Parent path: A parent path is a path that points to the parent directory of a file or
Page 06 of 02
22PLC15B/25B
directory. This can be specified using the ".." directory name. For example, if the
current working directory is "/home/user/mydir", then the parent directory can
be referred to as "../".
b Explain how to read specific lines from a file?. illustrate with python CO5 – L2 6
Program
To read specific lines from a file in Python, you can use a combination of the
open() function and the readlines() method. The open() function is used to
open the file in read mode, while the readlines() method is used to read all the
lines in the file and return them as a list of strings. Once you have the list of lines,
you can access specific lines by using list indexing.
Here's an example Python program that demonstrates how to read specific lines
from a file:
# Read all the lines in the file and store them in a list
.IN
lines = f.readlines()
open() function. We then use the readlines() method to read all the lines in the
file and store them in a list called lines.
c What is logging? how this would be used to debug the python program? CO3 – L3 8
U
logging module in Python provides a flexible and efficient way to handle logging
in Python programs.
Example -
import logging
logging.debug('The debug message is displaying')
logging.info('The info message is displaying')
logging.warning('The warning message is displaying')
logging.error('The error message is displaying')
logging.critical('The critical message is displaying')
Output:
Page 07 of 02
22PLC15B/25B
OR
Q. 06 a What is the use of ZIP? how to create a ZIP folder explain. CO3 – L2 6
Compressed ZIP files reduce the size of the original directory by applying
compression algorithm. Compressed ZIP files result in faster file sharing over a
network as the size of the ZIP file is significantly smaller than original file.
Example
Following is an example to create ZIP file using multiple files −
import os
from zipfile import ZipFile
.IN
# Check to see if the zip file is created
if os.path.exists('/home/secabiet/test.zip'):
print("ZIP file created")
else:
print("ZIP file not created")
OUTPUT
ZIP file created C
N
SY
U
VT
Page 08 of 02
22PLC15B/25B
b wite an algorithm for implement multi clipboard functionality CO5 – L2 6
.IN
c Discuss how lists would be written in the file and read from the file? CO3 – L3 8
C
Here's an example of how to write a list to a file:
# Define a list to write to the file
N
mylist = [1, 2, 3, 4, 5]
To read the list from the file, we can use the ast.literal_eval() function from the
ast module to safely evaluate the string as a Python expression:
VT
import ast
Module-4
Q. 07 a Define the terms with example: (i) class (ii) objects (iii) instance variables CO3 – L1 6
b create a Time class with hour, min and sec as attributes. Demonstrate how CO3 – L3 8
two Time objects would be added.
class Time:
hour=0
minute=0
second=0
def print_time(t):
print('%.2d:%.2d:%.2d' % (t.hour, t.minute, t.second))
def add_time(t1, t2):
sum=Time()
sum.hour = t1.hour + t2.hour
sum.minute = t1.minute + t2.minute
sum.second = t1.second + t2.second
.IN
return sum
t1 = Time()
t1.hour = 9
t1.minute = 45
t1.second = 0
t2 = Time()
t2.hour = 1 C
N
t2.minute = 35
t2.second = 0
t3 = Time()
SY
t3=Time.add_time(t1,t2)
Time.print_time(t3)
OUTPUT:
10:80:00
U
def __str__(self):
return f"Name: {self.name}, Age: {self.age}"
p = Person("John", 25)
print(p)
# Output:
Name: John, Age: 25
OR
Q. 08 a What is Encapsulation? Discuss with an example in which access CO3 – L2 4
specifiers are used in class definition.
Page 010 of
02
22PLC15B/25B
Encapsulation is a principle of object-oriented programming that involves
bundling data and methods that operate on that data within a single unit,
such as a class.
def _start_engine(self):
print("Engine started.")
.IN
def drive(self):
self._start_engine()
print("Driving...")
C
In this example, the attributes make, model, and year and the method
_start_engine are intended to be private, as indicated by the leading underscore
in their names.
N
These members are still accessible from outside the class, but it is a convention
that they should not be accessed directly.
SY
Instead, we should use the public methods of the class, such as the drive method,
which can call the private _start_engine method as needed.
b What is a class diagram? Create empty class and corresponding class CO3 – L3 8
U
diagram for following statements (i) class A derives from class B and
Class C (ii) Class D derived from Class A defined in statement (i)
VT
Using this syntax, we can create the following empty classes and
corresponding class diagram for the given statements:
class B:
pass
class C:
pass
OUTPUT:
B C
\ /
\/
A
Page 011 of
02
22PLC15B/25B
(ii) Class D derived from Class A defined in statement (i)
class D(A):
pass
OUTPUT:
B C
\ /
\/
A
|
D
.IN
# len() being used for a list
print(len([10, 20, 30]))
OUTPUT:
5
3
Example 2:
C
N
def add(x, y, z = 0):
return x + y+z
SY
# Driver code
print(add(2, 3))
print(add(2, 3, 4))
OUTPUT:
U
5
9
Module-5
VT
Page 012 of
02