0% found this document useful (0 votes)
3 views

Programming with Python important questions

The document is an answer key for a programming exam on Python at Bharati Vidyapeeth's College of Engineering, covering various topics such as modules, constructors, exception handling, namespaces, and inheritance. It includes definitions, explanations, and sample code for each topic, along with instructions for the exam. The document emphasizes the importance of understanding Python's object-oriented features and directory management functions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Programming with Python important questions

The document is an answer key for a programming exam on Python at Bharati Vidyapeeth's College of Engineering, covering various topics such as modules, constructors, exception handling, namespaces, and inheritance. It includes definitions, explanations, and sample code for each topic, along with instructions for the exam. The document emphasizes the importance of understanding Python's object-oriented features and directory management functions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

BHARATI VIDYAPEETH’S

COLLEGE OF ENGINEERING (DIPLOMA), KOLHAPUR.

Semester: Sixth Marks: 20


Sub: Programming with Python Time -1 hr.
Course: CO6I Code -22616
ANSWER KEY

Instructions:
1. All Questions are compulsory.

Q. 1 Attempt any four. (2*4= 08)


A. Define following:
1. Module
2. Package CO4
Ans.: Module: A module is a file containing definition of functions, classes, variables, constants or
any other Python object. Contents of this file can be made available to any other program. Python
has the import keyword for this purpose.
Package: Python packages are a way to organize and structure code by grouping related modules
into directories. A package is essentially a folder that contains an __init__.py file and one or more
Python files (modules).
B. How to create constructor method in python. CO5
Ans.: Python constructor is an instance method in a class, that is automatically called whenever a
new object of the class is created. The constructor's role is to assign value to instance
variables as soon as the object is declared.
Python uses a special method called __init__() to initialize the instance variables for the object.
e.g. def __init__(self, parameters):
#initialize instance variables
C. State use of ‘raise’ and ‘else’ statement in exception handling. CO6
Ans.: raise: Python raise Keyword is used to raise exceptions or errors. The raise keyword raises an
error and stops the control flow of the program. It is used to bring up the current exception in an
exception handler so that it can be handled further up the call stack.
Syntax: raise {name_of_ the_ exception_class}
else: The code enters the else block only if the try clause does not raise an exception. else block will
execute only when no exception occurs.
E.g.:
try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1/num
print(reciprocal)

D. Explain the term composition classes. CO5


Ans.: Composition is an object-oriented design concept that models a has a relationship. In
composition, a class known as composite contains an object, or component, of another class.
Composition allows composite classes to reuse the implementation of the components it
contains. The composite class doesn’t inherit the component class interface, but it can leverage its
implementation.
Syntax:
class A :
# variables of class A
# methods of class A
... ...
class B :
# by using "obj" we can access member's of class A.
obj = A()
# variables of class B
# methods of class B
... ...
E. Explain any four directory related standard function with syntax. CO6
Ans.: Python Directory Management refers to handling and interacting with directories (folders) on
a filesystem using Python.
 os.mkdir(path): Creates a single directory at the specified path. Raises an error if the
directory already exists.
 os.getcwd(): Returns the absolute path of the current working directory where the script is
running.
 os.rename(src, dst): Renames a directory (or file) from src to dst. The source (src) must
exist and the destination (dst) should not already exist.
 os.chdir(path): Changes the current working directory to the specified path.
 os.rmdir(path): Removes an empty directory.
 os.listdir(path): Returns a list of the names of files and directories in the specified
directory.
F. List different types of arguments used in function. CO4
Ans.:
1. Python Keyword Argument
2. Function Argument with Default Values
3. Python Function With Variable length Arguments
4. Required arguments

Q.2 Attempt any three. (4 *3 = 12)

A. Write a python program to find reverse of a given number using user defined function. CO4
Ans:
def findReverse(n):
reverse = 0
reminder = 0
while(n != 0):
remainder = n % 10
reverse = reverse * 10 + remainder
n = int(n / 10)
return reverse
num =int(input("input a number:"))
reverse = findReverse(num)
print('The reverse number is =', reverse)
B. Explain the concept of namespaces with an example. CO4
Ans.: A namespace is a system that has 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.
When Python interpreter runs solely without any user-defined modules, methods, classes, etc. Some
functions like print(), id() are always present, these are built-in namespaces. When a user creates a
module, a global namespace gets created, later the creation of local functions creates the local namespace.
The built-in namespace encompasses the global namespace and the global namespace encompasses
the local namespace. A lifetime of a namespace depends upon the scope of objects, if the scope of an
object ends, the lifetime of that namespace comes to an end. Hence, it is not possible to access the inner
namespace’s objects from an outer namespace.
global_var = 10

def outer_function():
# outer_var is in the local namespace
outer_var = 20
def inner_function():
# inner_var is in the nested local namespace
inner_var = 30
print(inner_var)

print(outer_var)
inner_function()
# print the value of the global variable
print(global_var)
# call the outer function and print local and nested local variables
outer_function()

C. Write a python program to read contents of first.txt file and write same content in
second.txt file. CO6
Ans.:
with open("first.txt", "r") as input:
with open("second.txt", "w") as output:
for line in input:
output.write(line)

D. Explain customization via inheritance specializing inherited methods. CO5


Ans.: 1) The tree-searching model of inheritance turns out to be a great way to specialize systems.
Because inheritance finds names in subclasses before it checks superclasses, subclasses can replace
default behavior by redefining the superclass's attributes.
2) You can build entire systems as hierarchies of classes, which are extended by adding new
external subclasses rather than changing existing logic in place.
3) The idea of redefining inherited names leads to a variety of specialization techniques.
For instance, subclasses may replace inherited attributes completely, provide attributes that a
superclass expects to find, and extend superclass methods by calling back to the superclass from an
overridden method.
4) Extension is the only way to interface with a superclass.
Super: Defines a method function and a delegate that expects an action in a subclass.
Inheritor: Doesn't provide any new names, so it gets everything defined in Super.
Replacer: Overrides Super's method with a version of its own.
Extender: Customizes Super's method by overriding and calling back to run the default.
Provider: Implements the action method expected by Super's delegate method.
E.g.
class super:
def method(self):
print("in super.method") #default behavior
def delegate(self):
self.action() #expected to be defined
class inheritor(super):
pass
class replacer(super): #replace method completely
def method(self):
print("in replacer.method")
class extender(super): #extend method behavior
def method(self):
super.method(self)
print("in extender.method")
class provider(super): # fill in a required method
def action(self):
print("in provider.action")
for klass in (inheritor,replacer,extender):
print("\n"+klass.__name__+"...")
klass().method()
print("\n provider...")
x=provider()
x.delegate()

E. Explain multiple inheritance and write a python program to implement it. CO5
Ans.: A class can be derived from more than one superclass in Python. This is called multiple
inheritance.
If a child class inherits from more than one class, i.e. this child class is derived
from multiple classes, we call it multiple inheritance in Python. This newly derived child class
will inherit the properties of all the classes that it is derived from.

class Parent1:
def m1(self):
print("m1 method of Parent1 class")

class Parent2:
def m2(self):
print("m2 method of Parent2 class")

class ChildClass(Parent1, Parent2):


def m3(self):
print("m3 method of ChildClass class")

child = ChildClass()
child.m1()
child.m2()
child.m3()

************************ ALL THE BEST ***************************

You might also like