Contact No: 9326050669 / 9326881428 - Youtube: @v2vedtechllp - Instagram: V2vedtech
Contact No: 9326050669 / 9326881428 - Youtube: @v2vedtechllp - Instagram: V2vedtech
Nextflix and Yelp have both documented the role of Python in their software infrastructures.
Industrial Light and Magic, Pixar and others uses Python in the production of animated movies.
Q 1 (c) Describe the Role of indentation in python. (W-23) 2 Marks Ans:
Indentation refers to the spaces at the beginning of a code line.
Generally, four whitespaces are used for indentation and is preferred over tabs.
Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.
Indentation helps to convey a better structure of a program to the readers. It is used to clarify the link
between control flow constructs such as conditions or loops, and code contained within and outside of
them.
Python uses indentation to indicate a block of code.
Figure of Indentation
Example:
if 5 > 2:
print("Five is greater than two!")
Q 3 a Explain building blocks of python. (W-23) 4 Marks Ans:
2) Reserved Words
The following list shows the Python keywords.
These are reserved words and cannot use them as constant or variable or any other identifier names.
All the Python keywords contain lowercase letters only except True and False.
Identity Operators:
Sometimes, in Python programming we need to compare the memory address of two objects.
This is made possible with the help of the identity operator.
Identity operators are used to check whether both operands are same or not.
Q 1 (b) Describe membership operators in python. (any four points) 2 Marks Ans:
Same as Winter 2023-2(a)
Q 2 (a) Describe Keyword "continue" with example. 4 Marks Ans:
Continue:
The continue statement in Python returns the control to the beginning of the while loop.
The continue statement rejects all the remaining statements in the current iteration of the
loop and moves the control back to the top of the loop.
Syntax:
continue
Example: For continue statement. i=0
while i<10:
i=i+1 if i==5:
continue
Output: print("i= ",i)
i=1
i=2
i=3
i=4
i=6
i=7
i=8
output:
i is 20
Q 3 (b) Write Python code for finding greatest among four numbers. 4 Marks Ans:
list1 = [ ]
num = int(input("Enter number of elements in list: ")) for i in range(1,
num + 1):
element = int(input("Enter elements: ")) list1.append(element)
print("Largest element is:", max(list1)) Output:
Enter number of elements in list: 4 Enter elements: 10
Enter elements: 20
Enter elements: 45
Enter elements: 20 Largest element is: 45
Summer-22
Q 1 (b) List identity operators in python. 2 Marks Ans:
Same as Winter 2023-2(a)
Example:
i=20
if(i<15):
if (i == 10):
print ("i is 10")
Winter-23
1(g) Explain two ways to add objects / elements to list. (2M) Ans:
1)append method:
The append() method adds an element to the end of a list. We can insert a single item in the list data time with
the append().
Example: Program for append() method.
>>> list1=[10,20,30]
>>> list1 [10, 20, 30]
>>> list1.append(40) # add element at the end of list
>>> list1
[10, 20, 30, 40]
2. extend() Method:
The extend() method extends a list by appending items. We can add several items using extend() method.
Example: Program for extend() method.
>>>list1=[10, 20, 30, 40]
>>>list1
[10, 20, 30, 40]
>>> list1.extend([60,70]) #add elements at the end of list
>>> list1
[10, 20, 30, 40, 60, 70]
3. insert() Method:
We can insert one single item at a desired location by using the method insert() or insert multiple items by
squeezing it into an empty slice of a list.
Example: Program for insert() method.
>>> list1=[10, 20]
>>>list1 [10,20]
>>> list1.insert(1,30)
>>> list1 [10, 30, 20]
2(c) Explain four built-in list functions.. (4M) Ans:
>>> list1
[1, 2, 3, 4, 5]
It adds the elements of the sequence at >>> list2
8 list.extend(seq) the end of the list.
['A', 'B', 'C']
>>> list1.extend(list2)
>>> list1
[1, 2, 3, 4, 5, 'A', 'B', 'C']
>>> list1
list.pop(item=list[-1]) It deletes and returns the last element [1, 2, 7, 3, 4, 5, 3]
9 of the list. >>> list1.pop()
3
>>> list1.pop(2)
7
3(c) (4M)
T = ('spam, Spam', SPAM!', 'SaPm') print (T [2])
print (T[-2])
print (T[2:]) print (List (T)) Ans:
Python statement Output
print (T [2]) SPAM!
print (T[-2]) SPAM!
print (T[2:]) [‘SPAM!', 'SaPm']
print (list (T)) ['spam', 'Spam', 'SPAM!', 'SaPm']
4(a) Explain different functions or ways to remove key : value pair from Dictionary. (4M) Ans:
pop():
We can remove a particular item in a dictionary by using the method pop(). This method removes
as item with the provided key and returns the value.
Example:
>>> squares
{1: 1, 2: 4, 3: 9, 4: 16}
>>> squares.pop(2) # remove a particular item 4
>>> squares
{1: 1, 3: 9, 4: 16}
Popitem():
The method, popitem() can be used to remove and return an arbitrary item (key, value) form the
dictionary.
Example:
>>> squares={1:1,2:4,3:9,4:16,5:25}
>>> squares
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
>>> print(squares.popitem()) # remove an arbitrary item (5, 25)
>>> squares
{1: 1, 2: 4, 3: 9, 4: 16}
Clear():
All the items can be removed at once using the clear() method.
Example:
>>> squares
{1: 1, 4: 16}
>>> squares.clear() # removes all items
>>> squares
{}
Del():
We can also use the del keyword to remove individual items or the entire dictionary itself.
Example:
>>> squares
{1: 1, 3: 9, 4: 16}
>>> del squares[3] # delete a particular item
>>> squares
{1: 1, 4: 16}
5(a) Explain any four set operations with example. (6M) Ans:
Set Operations:
1. Set Union:
The union of two sets is the set of all the elements of both the sets without duplicates.
We can use the ‘|’ operator to find the union of a Python set.
>>> first_set = {1, 2, 3}
>>> second_set = {3, 4, 5}
>>> first_set.union(second_set)
{1, 2, 3, 4, 5}
>>> first_set | second_set # using the ‘|’ operator
{1, 2, 3, 4, 5}
2. Set Intersection:
The intersection of two sets is the set of all the common elements of both the sets.
We can use the ‘&’ operator to find the intersection of a Python set.
>>> first_set = {1, 2, 3, 4, 5, 6}
>>> second_set = {4, 5, 6, 7, 8, 9}
>>> first_set.intersection(second_set)
{4, 5, 6}
>>> first_set & second_set # using the ‘&’ operator
{4, 5, 6}
3. Set Difference:
The difference between two sets is the set of all the elements in first set that are not present in the
second set.
We can use the ‘–‘ operator to achieve this in Python.
>>> first_set = {1, 2, 3, 4, 5, 6}
>>> second_set = {4, 5, 6, 7, 8, 9}
>>> first_set.difference(second_set)
{1, 2, 3}
>>> first_set - second_set # using the ‘-‘ operator
{1, 2, 3}
6(c) List and explain any four built-in functions on set. (6M) Ans:
Built-in Functions with Set :
1) add()
2) discard()
3) copy()
4) remove()
5) clear()
6) union()
7) difference()
8) intersection()
9) discard()
10) issubset()
11) issuperset()
12) pop()
13) update()
14) symmetric_difference()
add(): Adds an element to the set. If an element is already exist in the set, then it does not
add that element.
Example:
s = {'g', 'e', 'k', 's'}
# adding f into set s
s.add('f')
print('Set after updating:', s)
output:
Set after updating: {'s', 'f', 'e', 'g', 'k'}
discard():
Removes the element from the set
Example:
s = {'g', 'e', 'k', 's'}
print('Set before discard:', s) s.discard('g')
print('\nSet after discard g:', s)
Output:
Removes the specified element from the set. If the specified element not found, raise
an error.
Example:
s = {'g', 'e', 'k', 's'}
print('Set before remove:', s)
s.remove('e')
print('\nSet after remove e:', s)
Output:
Set before remove: {'s', 'k', 'e', 'g'}
Set after remove e: {'s', 'k', 'g'}
clear():
Removes all elements from the set
Example:
s = {'g', 'e', 'k', 's'}
print('Set before clear:', s)
s.clear()
print('\nSet after clear:', s)
Output:
Set before clear: {'g', 'k', 's', 'e'}
Set after clear: set()
copy():
Returns a shallow copy of the set
Example:
s = {'g', 'e', 'k', 's'}
p=s.copy()
print("original set:",s)
print("Copied set:",p)
Output:
original set: {'k', 's', 'g', 'e'}
Copied set: {'k', 's', 'g', 'e'}
Union():
The set.union() method returns a new set with distinct elements from all the given sets.
Example:
nums1 = {1, 2, 2, 3, 4, 5}
nums2 = {4, 5, 6, 7, 7, 8}
distinct_nums = nums1.union(nums2) print("The union of two
sets is: ", distinct_nums)
Output:
The union of two sets is: {1, 2, 3, 4, 5, 6, 7, 8}
Difference():The set.difference() method returns the new set with the unique elements that are not in the other set
passed as a parameter.
Example:
nums1 = {1, 2, 2, 3, 4, 5}
2(b) Explain creating Dictionary and accessing Dictionary Elements with example. (6M) Ans:
Creating Dictionary
The simplest method to create dictionary is to simply assign the pair of keys: values to the dictionary
using operator (=).
• There are two ways for creation of dictionary in python.
1. We can create a dictionary by placing a comma-separated list of key: value pairs in curly braces {}.
Each key is separated from its associated value by a colon:
Example: For creating a dictionary using { }.
>>> dict1={} #Empty dictionary
>>> dict1
{}
>>> dict2={1:"Orange", 2:"Mango", 3:"Banana"} #Dictionary with integer keys
>>> dict2
The bin() function returns the binary version of a specified integer. The result will always start
with the prefix 0b
Example:
'0b1010' with the prefix 0b.
10. bool()
The bool() function returns the boolean value of a specified object.
Example:
>>> bool(1) True
11. exp()
The method exp() returns returns exponential of x: ex. x: This is a
numeric expression.
Example:
Contact No : 9326050669 / 9326881428 | Youtube : @v2vedtechllp | Instagram : v2vedtech
>>> math.exp(1) 2.718281828459045
3(a) Write a python program to input any two tuples and interchange the tuple variables. (4M)
Ans:
def interchange_tuples(tup1, tup2): new_tup1 = tup2
new_tup2 = tup1
return new_tup1, new_tup2
# Input two tuples
tuple1 = tuple(input("Enter the elements of the first tuple (separated by commas): ").split(","))
tuple2 = tuple(input("Enter the elements of the second tuple (separated by commas): ").split(","))
# Interchange the tuples
result_tuple1, result_tuple2 = interchange_tuples(tuple1, tuple2)
3 Lists are better for insertion and deletion Tuples are appropriate for accessing the
operations elements
4 Lists consume more memory Tuples consume lesser memory
5 Lists have several built-in methods Tuples have comparatively lesser built-in
methods.
6 Lists are more prone to unexpected errors Tuples operations are safe and chances of
error are very less
8 Lists are initialized using square brackets []. Tuples are initialized using parentheses ().
set1 = {1, 2, 3}
set2 = {2, 3, 4}
intersection_set = set1.intersection(set2) print(intersection_set)
Output:
{2, 3}
3) Difference:
Difference operation on two sets set1 and set2 returns all the elements which are present on set1
but not in set2.
Example:
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4}
difference_set = set1.difference(set2) print(difference_set) #
Output: {1, 2, 5}
>>> car = {
Returns the value of the "brand": "Ford",
specified key. If the key does "model": "Mustang",
9 setdefault() not exist: insert the key, with "year": 1964 }
the specified value >>>x=car.setdefault("model",
"Bronco")
>>>print(x)
Mustang
>>> car = {
"brand": "Ford",
"model": "Mustang",
update() Updates the dictionary with the "year": 1964 }
10 >>>car.update({"color":"White"})
specified key-value pairs
>>>print(car)
{'brand': 'Ford', 'model':
'Mustang', 'year': 1964, 'color':
'White'}
>>> car = {
"brand": "Ford",
Returns a list of all the values in "model": "Mustang",
11 values() the dictionary "year": 1964 }
>>>x = car.values()
>>>print(x)
dict_values(['Ford', 'Mustang',
1964])
>>> car = {
Returns true if all keys of the "brand": "Ford",
12 all() dictionary are true(or if the "model": "Mustang",
dictionary is empty ) "year": 1964 }
>>>all(car)
True
Returns true if any keys if >>> car = { }
13 any() dictionary is not empty and >>>any(car)
false if dictionary is empty False
>>> car = {
Returns total number of "brand": "Ford",
14 Len() element in the dictionary "model": "Mustang",
"year": 1964 }
>>>len(car)
3
List Dictionary
The list is a collection of index value pairs The dictionary is a hashed structure of the
like that of the array in C++. key and value pairs.
The list is created by placing elements The dictionary is created by placing
in [ ] separated by commas “,” elements in { } as “key”:”value”, each key-
value pair is separated by commas “, “
The indices of the list are integers The keys of the dictionary can be of any data
starting from 0. type.
The elements are accessed via indices. The elements are accessed via key-value
pairs.
The order of the elements entered is There is no guarantee for maintaining order.
maintained.
Lists are orders, mutable, and can contain Dictionaries are unordered and mutable but
duplicate values. they cannot contain duplicate keys.
# To Create set
S={10,20,30,40,50}
S.update(['
A','B'])
print(S)
6. Sets:
Set is an unordered and unindexed collection of items in Python.
Unordered means when we display the elements of a set, it will come out in a random order.
Unindexed means, we cannot access the elements of a set using the indexes like we can do in list and
tuples.
The elements of a set are defined inside curly brackets and are separated by commas.
Example:
myset = {1, 2, 3, 4, "hello"}
Summer-22
Q 1 (c) Give two differences between list and tuple. 2 Marks Ans:
Q 2 (b) Explain four Buit-in tuple functions in python with example
ii)
>>>dict1[2]="Shreyas"
>>>print(dict1)
{1: 'Vijay', 2: 'Shreyas', 3: 'Yogita'}
iii)
>>>dict1.pop(1)
‘Vijay'
>>>print(dict1)
{2: 'Shreyas', 3: 'Yogita'}
Winter-23
1(e) State use of namespace in python. (2M) Ans:
Namespaces bring you three advantages: they group names into logical containers, they prevent
clashes between duplicate names, and third, they provide context to names.
Namespaces prevent conflicts between classes, methods and objects with the same name that might
have been written by different people.
A namespace is a system to have a unique name for each and every object in Python. An object might
be a variable or a method. Python itself maintains a namespace in the form of a Python dictionary.
A namespace in python is a collection of names. So, a namespace is essentially a mapping of
names to corresponding objects.
2(d) Write python program using module, show how to write and use module by importing it.
(4M)
Ans:
For creating a module write following code and save it as p1.py #p1.py
def add(a, b):
#This function adds two numbers and return the result result = a + b
return result
def sub(a, b):
#This function subtracts two numbers and return the result result = a - b
return result
Import the definitions inside a module:
import p1 print(p1.add(10,20))
print(p1.sub(20,10))
Output:
30
10
4(b) Explain Numpy package in detail. (4M) Ans:
NumPy is the fundamental package for scientific computing with Python. NumPy stands for
"Numerical Python". It provides a high-performance multidimensional array object, and tools for
working with these arrays.
An array is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive
integers and represented by a single variable. NumPy's array class is called ndarray. It is also known by
the alias array.
In NumPy arrays, the individual data items are called elements. All elements of an array should be
of the same type. Arrays can be made up of any number of dimensions.
In NumPy, dimensions are called axes. Each dimension of an array has a length which is the total
number of elements in that direction.
The size of an array is the total number of elements contained in an array in all the dimension. The
size of NumPy arrays are fixed; once created it cannot be changed again.
Numpy arrays are great alternatives to Python Lists. Some of the key advantages of Numpy arrays are
that they are fast, easy to work with, and give users the opportunity to perform calculations across
entire arrays.
A one-dimensional array has one axis indicated by Axis-0. That axis has five elements in it, so we say it
has length of five.
A two-dimensional array is made up of rows and columns. All rows are indicated by Axis-0 and all
columns are indicated by Axis-1. If Axis-0 in two-dimensional array has three elements, so its length it
three and Axis-1 has six elements, so its length is six.
Commands to install numpy in window, Linux and MAC OS:
1) python -m pip install numpy
2) To use NumPy you need to import Numpy:
3) import numpy as np # alias np
Using NumPy, a developer can perform the following operations:
1) Mathematical and logical operations on arrays.
2) Fourier transforms and routines for shape manipulation.
3) Operations related to linear algebra.
4) NumPy has in-built functions for linear algebra and random number generation.
5 (c) Write a program illustrating use of user defined package in python. (6M)
Ans:
# student.py
class Student:
def init (self, student):
self.name = student['name'] self.gender =
student['gender'] self.year = student['year']
def get_student_details(self):
return f"Name: {self.name}\nGender: {self.gender}\nYear: {self.year}"
# faculty.py
class Faculty:
def init (self, faculty):
self.name = faculty['name'] self.subject =
faculty['subject'] def get_faculty_details(self):
return f"Name: {self.name}\nSubject: {self.subject}"
# testing.py
# importing the Student and Faculty classes from respective files from student import
Student
from faculty import Faculty
# creating dicts for student and faculty
student_dict = {'name' : 'ABC', 'gender': 'Male', 'year': '3'} faculty_dict = {'name':
'XYZ', 'subject': 'Programming'}
Contact No : 9326050669 / 9326881428 | Youtube : @v2vedtechllp | Instagram : v2vedtech
# creating instances of the Student and Faculty classes student =
Student(student_dict)
faculty = Faculty(faculty_dict)
# getting and printing the student and faculty details print(student.get_student_details())
print() print(faculty.get_faculty_details())
Output :
Name: ABC Gender: Male Year: 3
Name: XYZ
Subject: Programming
Summer-23
4(d) Explain Module and its use in Python. (4M) Ans:
Modules:
Modules are primarily the (.py) files which contain Python programming code defining functions,
class, variables, etc. with a suffix .py appended in its file name.
A file containing .py python code is called a module.
If we want to write a longer program, we can use file where we can do editing, correction. This is
known as creating a script. As the program gets longer, we may want to split it into several files for
easier maintenance.
We may also want to use a function that you’ve written in several programs without
copying its definition into each program.
In Python we can put definitions in a file and use them in a script or in an interactive instance of the
interpreter. Such a file is called a module.
Use of module in python : Code organization:
Modules allow you to organize related code into separate files, making it easier to navigate and
maintain large projects.
Code reusability:
Modules can be imported and reused in multiple programs, enabling code reuse and reducing duplication.
Encapsulation:
Modules provide a way to encapsulate code and hide the implementation details, allowing users to focus
on the functionality provided by the module.
Name spacing:
Modules help avoid naming conflicts by providing a separate namespace for the names defined within
the module. 5(b) Write a Python program to calculate sum of digit of given number using function. (6M)
Ans:def calculate_digit_sum(number):
# Convert the number to a string num_str = str(number)
# Initialize a variable to store the sum digit_sum = 0
# Iterate over each character in the string for digit in num_str:
# Convert the character back to an integer and add it to the sum digit_sum += int(digit)
# Return the sum of the digits return digit_sum
# Test the function
input_number = int(input("Enter a number: ")) sum_of_digits =
calculate_digit_sum(input_number) print("Sum of digits:", sum_of_digits)
output:
Enter a number: 123 Sum of digits: 6
ns:
The lambda function, which is also called anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
Syntax:
lambda arguments : expression
Example:
x= lambda a,b : a*b Print(x(10,5)
Output:
50
2(c) What is local and global variables? Explain with appropriate example. (2M) Ans:
Global variables: global variables can be accessed throughout the program body by all functions.
Local variables: local variables can be accessed only inside the function in which they are declared
Concept Diagram:
A global variable (x) can be reached and modified anywhere in the code, local variable (z) exists
only in block 3.
Example:
g=10 #global variable g def test():
l=20 #local variable l print("local variable=",l)
# accessing global variable print("Global
variable=",g) test()
print("global variable=",g)
output:
local variable= 20
Global variable= 10
global variable= 10
5(b) Example module. How to define module. (6M) Ans
A module allows you to logically organize your Python code.
Grouping related code into a module makes the code easier to understand and use.
A module is a Python object with arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code.
A module can define functions, classes and variables. A module can also include runnable code.
Example:The Python code for a module named aname normally resides in a file named
aname.py. Here is an example of a simple module, support.py
#empty placeholders:
>>>txt3 = ("My name is {}, I'm {}".format("pqr",36))
>>>print(txt3)
My name is pqr, I'm 36
4(e) Write a program illustrating use of user defined package in python. (4M) Ans:
A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules and subpackages and sub- subpackages, and so on.
Packages allow for a hierarchical structuring of the module namespace using dot notation.
Creating a package is quite straightforward, since it makes use of the operating
system’s inherent hierarchical file structure.
Here, there is a directory named pkg that contains two modules, mod1.py and mod2.py.
The contents of the modules are:
mod1.py
def m1():
print("first module")
Syntax-3:
from <module_name> import <name> as <alt_name>
Example:
>>> from pkg.mod1 import m1 as module
>>> module() first module
1(d) Define Data Hiding concept? Write two advantages of Data Hiding. (2M) Ans:
Data hiding:
Data hiding is a concept which underlines the hiding of data or information from the user.
Data hiding is a software development technique specifically used in Object-Oriented Programming
(OOP) to hide internal object details (data members).
Data hiding includes a process of combining the data and functions into a single unit to conceal data
within a class by restricting direct access to the data from outside the class.
Advantages of Data Hiding
Data hiding ensures exclusive data access to class members and protects object integrity by
preventing unintended or intended changes.
Data hiding is also known as information hiding. An object's attributes may or may not be visible
outside the class definition.
Data hiding also minimizes system complexity for increase robustness by limiting
interdependencies between software requirements.
The objects within the class are disconnected from irrelevant data.
It heightens the security against hackers that are unable to access confidential data.
It helps to prevent damage to volatile data by hiding it from the public.
Summer-23
1(d) With neat example explain default constructor concept in Python. (2M) Ans:
Default constructor:
The default constructor is simple constructor which does not accept any arguments.
It’s definition has only one argument which is a reference to the instance being
constructed.
Example : Display Hello message using default constructor. class Student:
def _ _init_ _(self):
print("This is non parametrized constructor") def
show(self,name):
print("Hello",name)
s1 = Student() s1.show("Student1") Output:
This is non parametrized constructor Hello Student1
def get_info(self):
info = f"Make: {self.make}, Model: {self.model}, Year: {self.year}" return info
2022)
Engine started!
6(b) Design a class student with data members : name, roll no., department, mobile no. Create suitable methods
for reading and printing student information.(6M)
Ans:
class Student:
def init (self):
self.name = "" self.roll_no = ""
self.department = "" self.mobile_no = ""
def read_student_info(self):
self.name = input("Enter student name: ") self.roll_no = input("Enter
roll number: ") self.department = input("Enter department: ")
self.mobile_no = input("Enter mobile number: ")
student.print_student_info()
Output:
Enter student name: raj Enter roll number:
11
Enter department: computer Enter mobile
number: 123456 Student Information:
Name: raj
Roll Number: 11 Department: computer
Mobile Number: 123456
6(c) With suitable example explain inheritance in Python. (6M) Ans:
Inheritance:
In inheritance objects of one class procure the properties of objects of another class.
Inheritance provides code usability, which means that some of the new features can be added to the
code while using the existing code.
The mechanism of designing or constructing classes from other classes is called inheritance.
The new class is called derived class or child class and the class from which this derived class has
been inherited is the base class or parent class.
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.
Syntax:
class A:
# properties of class A
class B(A):
# class B inheriting property of class A # more properties
of class B
Example:
# Base class class Animal:
def init (self, name):
self.name = name def speak(self):
print("Animal speaks")
# child class
class Herbivorous(Animal):
# function feed
def feed(self):
print("I eat only plants. I am vegetarian.") herbi =
Herbivorous()
herbi.feed()
# calling some other function herbi.breathe()
Output:
I eat only plants. I am vegetarian. I breathe oxygen.
Summer-22
1(e) Define class and object in python. (2M) Ans:
Class:
Object:
An object is an instance of a class that has some attributes and behavior. Objects can be used to access the
attributes of the class.
3(d) Write a program to create class EMPLOYEE with ID and NAME and display its contents.(4M) Ans:
class employee :
id=0 name=""
def getdata(self,id,name): self.id=id
self.name=name
def showdata(self):
print("ID :", self.id) print("Name :", self.name)
e = employee() e.getdata(11,"Vijay")
e.showdata()
Output:
ID : 11
Name : Vijay
5(b) Explain method overloading in python with example. (6M) Ans:
Same as Winter 2023-3(d)
6(b) Write a program to implement the concept of inheritance in python.(6M) Ans:
Same as Summer 2023-6(c)
Unit 6- File I/O Handling and Exception Handling
Winter-23
1(f) State the use of read() and readline () functions in python file handling. (2M) Ans:
1. read([n]) Method:
The read method reads the entire contents of a file and returns it as a string, if number of bytes are not given in
the argument. If we execute read(3), we will get back the first three characters of the file.
Example: for read( ) method. f=open("sample.txt","r")
print(f.read(5)) # read first 5 data print(f.read()) # read
rest of the file
4(c) Explain seek ( ) and tell ( ) function for file pointer manipulation in python with example. (4M)
Ans:
seek():
seek() function is used to shift/change the position of file object to required position.
By file object we mean a cursor. And it’s cursor, who decides from where data has to
be read or write in a file.
Syntax:
f.seek(offset, fromwhere)
where offset represents how many bytes to move fromwhere, represents the position from where the
bytes are moving.
Example:
f = open("demofile.txt", "r")
f.seek(4) #sets Reference point to fourth index position from the beginning print(f.readline())
tell():
tell() returns the current position of the file pointer from the beginning of the file.
Syntax: file.tell()
Example:
f = open("demofile.txt", "r") # points at the
start print(f.tell())
4(c) WAP to read contents of first.txt file and write same content in second.txt file. (4M) Ans:
with open('first.txt', 'r') as f: # Open the first file for reading contents = f.read() #
Read the contents of the file
with open('second.txt', 'w') as f: # Open the second file for writing f.write(contents) # Write the
contents of the first file to the second file
Summer-23
1(f) Describe mkdir() function. (2M) Ans:
We can make a new directory using the mkdir() method.
This method takes in the path of the new directory. If the full path is not specified, the new directory
is created in the current working directory.
This method reads all lines from the file and returns them as a list of strings.
Each line is an individual element in the list.
It reads the entire file content and stores it in memory.
Example:
# Open the file in read mode file =
open("example.txt", "r") # Read all lines
lines = file.readlines() # Close the file
file.close()
# Print each line for line in lines:
print(line)
4(c) Write a program to show user defined exception in Python. (4M) Ans:
class MyException(Exception): def init (self,
message):
self.message = message
divide_numbers(a, b):
4(c) Write python code to count frequency of each characters in a given file.(4M)
Ans:
import collections import pprint