Programming with Python important questions
Programming with Python important questions
Instructions:
1. All Questions are compulsory.
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)
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")
child = ChildClass()
child.m1()
child.m2()
child.m3()