VR20 Python Lab Manual For Print
VR20 Python Lab Manual For Print
AY: 2020-21
Regulation: R20
LAB MANUAL
Faculty Coordinator:
PO PO PO PO PO PO PO PO PO PO PO PO PSO
1 2 3 4 5 6 7 8 9 10 11 12 1
CO1 M M L M L H
CO2 L M L L
CO3 L L L L M
CO4 M M M M H
ii
Page
Week Experiment CO
No.
Understanding Object Oriented
1 1,4 1
Programming, Python installation.
Declaration of Variables,
2 1 1
identifiers and type conversions
Python programs on Decision Control
3 1 5
Statements.
Python programs on looping control
4 1 7
structures.
Identify the need and importance in
5,6 the creation of Python Functions 2 10
and Modules.
Solve the problems using Strings
7 and understanding the methods and 2 16
operations on Lists.
Programs on the implementation of
8 methods and operations of List data 3 18
structure.
Implement programs to solve the
problems using Python other data
9 3 20
structures: Tuples and
Dictionaries.
Implement the Python Classes and
10,11 Objects to address the real-world 4 22
scenarios.
Develop the programs to implement
12,13 4 30
parent-child relationship
Write the programs to address the
exceptions via exception handling
14 4 37
in the development of solutions and
implement operator overloading
iii
Week wise Tasks with Solutions & sample outputs
Week – 1
1 Install python for Windows and ubuntu from https://www.python.org/downloads/
2 Install Jupyter Notebook and Execute the first “Hello world” Program on both Jupyter cell
environment and Python prompt as well.
3 Write a python program to print two strings/objects (“This is our” , “Second Program”) by
separator “,” and supress the newline character and print “ENDLINE” at the end
Sol:
n=input()
m=input()
print(n, m,sep=',',end='ENDLINE')
Output:
This is our
Second program
This is our,Second programENDLINE
Week – 2
1 Python Program to Check if a Number is Odd or Even
Sol:
n= int(input("Enter a number"))
if(n%2==0):
print("Even number")
else:
print("Odd number")
Output:
Enter a number2
Even number
Sol:
1
d1=d**0.5
if(d<0):
print("The roots are imaginary. ")
else:
r1=(-b+d1)/2*a
r2=(-b-d1)/2*a
print("The first root: ",round(r1,2))
print("The second root: ",round(r2,2))
Output:
Equation: ax^2 + bx + c
Enter a: 10
Enter b: 5
Enter c: 3
The roots are imaginary
Sol:
Output:
Sol:
2
a=a-b
print("After swapping:",a,b)
Output:
Enter 2 numbers :2 3
Before swapping: 2 3
After swapping: 3 2
Sol:
# conversion factor
conv_fac = 0.621371
# calculate miles
miles = kilometers * conv_fac
print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles))
Output:
Enter value in kilometers: 100
100.00 kilometers is equal to 62.14 miles
Sol:
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
Output:
3
Enter a year: 2021
2021 is not a leap year
Sol:
# initialize sum
sum = 0
Output:
Sol:
Output:
4
Enter a number: 5
Positive number
Week - 3
1 Accept the following from the user and calculate the percentage of class attended:
a. Total number of working days
b. Total number of days for absent
After calculating percentage show that, If the percentage is less than 75, than
student will not be able to sit in exam.
Sol:
Output:
2 Write a program to accept the cost price of a bike and display the road tax to be paid
according to the following criteria:
Cost price (in Rs) Tax
> 100000 15 %
> 50000 and <= 10%
100000
<= 50000 5%
Sol:
5
Output:
3 Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range print
an error. If the score is between 0.0 and 1.0, print a grade using the following Score Grade:
Score Grade
>= 0.9 A, >= 0.8 B, >= 0.7 C, >= 0.6 D, < 0.6 F
Sol:
Output:
Sol:
while True:
n=int(input("Enter the number to be convereted into binary number"))
if(n<0):
continue
if(n==999):
break
print(bin(n))
6
Output:
Enter the number to be convereted into binary number5
0b101
5 The ExConFair is the region's largest trade fair on Construction Equipment & Technology.
The Event organizers hired college students as volunteers to work at the fair as the event is
targeted to be attended by approx. 30 million visitors. At the Office in the fair, there are two
guards who count how many times a volunteer enters into the fair ground. Though the duty of
a guard is 24 hour in a day, but sometimes they fall asleep during their duty and could not
track the entry of volunteers in the fair ground. But one better thing is that they never fall
asleep at the same time. At least one of them remains awake and counts who enters into the
office. Now the Event Head wants to calculate how many times a volunteer has entered into
the fair ground. He asked to the guard and they give him two integers A and B, count of first
guard and second guard respectively. Help the Event Head to count the minimum and
maximum number of times a volunteer could have entered into the fair ground.
Sample Input 1: 19 17, Sample Output 1:19 36
Sample Input 2: 30 40, Sample Output 2: 40 70
Sol:
Output:
Week – 4
1 Write a python program to construct the following patterns using nested for loop
* 1 1
** 12 22
*** 123 333
**** 1234 4444
***** 12345 55555
***** 123456 666666
****
***
**
*
7
a. Sol:
Output:
b. Sol
Output:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
c. Sol
8
for row in range(1, r+1):
for column in range(1, row + 1):
print(column, end=' ')
print("")
Output:
2 Write a python program to print Multiplication table using format function inside print
Sol:
n=int(input("Enter a number:"))
for i in range(1,11):
print("{}*{}={}".format(n,i,n*i))
Output:
Enter a number:5
5*1=5
5*2=10
5*3=15
5*4=20
5*5=25
5*6=30
5*7=35
5*8=40
5*9=45
5*10=50
3 Write a Python Program to Check how many times a given number can be divided by 3
before it is less than or equal to 10.
Sol:
n = int(input())
count = 0
while n>=10:
if n%3==0:
count+=1
n//=3
print(count)
9
Output:
81
2
4 Calculate the sum of the first 20 items of 1 + 2 + 4 + 8 + 16 +… using while True infinite
loop with break statement.
Sol:
s=0
i=0
while i<=20:
s=s+2**i
i=i+1
print(s)
Output:
2097151
5 Transform the existing while loops with calculations 0-100, and add continue statements to
calculate only the odd sums.
Sol:
s=0
n=1
while n<=100:
if(n%2!=0):
s=s+n
n=n+1
else:
n=n+1
continue
print("The odd sum is:",s)
Output:
Week 5 & 6
1 Understand the usage of methods in python
a. Create a Python script with two methods which will compute the area and the perimeter
of a circle.
Sol:
10
r=float(input("Enter radius: "))
pie=3.14
print("The perimeter and area :{0},{1}".format(2*pie*r,pie*r*r))
Output:
Enter radius: 5
The perimeter and area :31.400000000000002,78.5
b. Create a Python script which takes length & width from the user and two methods
which will compute the area & perimeter of a rectangle.
Sol:
Output:
Enter length and breadth:5 6
Area and perimeter are:30,22
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
GCD=gcd(a,b)
print("GCD is: ",GCD)
Output:
11
def lcm(a,b):
lcm.multiple=lcm.multiple+b
if((lcm.multiple % a == 0) and (lcm.multiple % b == 0)):
return lcm.multiple;
else:
lcm(a, b)
return lcm.multiple
lcm.multiple=0
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
if(a>b):
LCM=lcm(b,a)
else:
LCM=lcm(a,b)
print("LCM is:",LCM)
Output:
Sol:
def fact(m):
n=1
f=1
while n<=m:
f=f*n
n=n+1
return f
m=int(input("Enter a number:"))
print(" The factorial is :",fact(m))
Output:
Enter a number:5
The factorial is : 120
Sol:
def Feb(n):
12
n1, n2 = 0, 1
count = 0
if n <= 0:
print("Please enter a positive integer")
elif n == 1:
print("Fibonacci sequence upto",n,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < n:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
n=int(input("Enter a number:"))
Feb(n)
Output:
Enter a number:8
Fibonacci sequence:
0
1
1
2
3
5
8
3 Solve the following tasks by using different types of using arguments in python.
a. Create a function showEmployee() in such a way that it should accept employee name,
and its salary and display both. If the salary is missing in the function call assign default
value 10,000 to salary. Hint: Use the concept of default length argument concept in
python.
Sol:
def showEmployee(name,salary='10000'):
print(name,salary)
showEmployee('priya')
13
Output:
priya 10000
marks(5,10,10,10,40,10)
Output:
The total and average : 80 16.0
4 You are given a date. Your task is to find what the day is on that date.
Input Format
A single line of input containing the space separated month, day and year, respectively, in
MM DD YY
format. Constraints : 2000<year<3000
Sample Input
08 05 2015
Sample Output
WEDNESDAY
Sol:
import datetime
date=str(input('Enter the date(for example:09 02 2019):'))
day_name= ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday','Sunday']
day = datetime.datetime.strptime(date, '%d %m %Y').weekday()
print(day_name[day])
Output:
Enter the date(for example:09 02 2019):01 01 2021
14
Friday
Sol:
import numpy as np
R = int(input("Enter the number of rows:"))
C = int(input("Enter the number of columns:"))
entries = list(map(int, input().split()))
a = np.array(entries).reshape(R, C)
entries = list(map(int, input().split()))
b= np.array(entries).reshape(R, C)
print(np.add(a,b))
print(np.subtract(a,b))
print(np.multiply(a,b))
print(np.divide(a,b))
print(np.mod(a,b))
print(np.power(a,b))
15
Output:
Week 7
1 Write a python program to calculate the class average by taking students name as string,
student roll number as integer, five subject marks from the user and display name, roll
number, marks, all subjects marks and average with precision with 2 using string formatting.
(Hint: String format %s, %d, %f)
Sol:
Output:
2 Given a string and two substrings, write a Python program to extract the string between the
16
found two substrings
Sol:
s = input()
sub1,sub2 = map(str,input().split())
if sub1 in s and sub2 in s:
result = s[s.index(sub1)+len(sub1)+1:s.index(sub2)]
print(result)
else:
print("Substrings are not present in the main string")
Output:
ab bc
bc fd
Substrings are not present in the main string
3 Given Strings with words, the task is to write a Python program to split each word into two
halves on the basis of assigned percentages according to the given values.
(Sample Input: “VR Siddhartha Engineering College is Best College in AP”, per=50
Output: “ V R Siddh artha Engine eering Coll ege i s Be st Coll ege i n A P” )
Sol:
s = input().split()
percent = int(input())
result = ""
for i in s:
val = int((percent/100)*len(i))
s1,s2 = i[:val],i[val:]
result += s1+" "+s2+" "
print(result)
Output:
4 Write a Python program to find all adverbs and their positions in a given sentence.
(Sample Input: "Clearly, he has no excuse for such behavior." Output: 0-7: Clearly )
5 Given a string, the task is to write a Python program to extract date from it.
Sample Input: “VRSEC at 2021-07-06” Output: 0-7: 2021-07-06, Hint: re.search(),
strptime() )
Sol:
17
import re
for m in re.finditer(r"\w+ly",input()):
print('%d-%d: %s' % (m.start(), m.end(), m.group(0)))
Output:
Week – 8
1 Write a program which accepts a sequence of comma-separated numbers from console and
generate a list and a tuple which contains every number. Suppose the following input is
supplied to the program: 34, 67, 55, 33, 12, 98. Then, the output should be: ['34', '67', '55',
'33', '12', '98'] ('34',67', '55', '33', '12', '98').
Sol:
s=input().split(",")
li=list(s)
tu=tuple(li)
print(li)
print(tu)
Output:
2 Write a python program to find tuples which have all elements divisible by K from a list of
tuples.
Sol:
lt=[(12,45,63),(3,5,9),(15,27,61),(90,72,24)]
k=int(input("Enter k value: "))
for i in lt:
c=0
for j in i:
if j%k!=0:
c=1
break
if c==0:
print(i,end=" ")
Output:
18
Enter k value: 3
(12, 45, 63) (90, 72, 24)
3 Write a python program to find Tuples with positive elements in List of tuples.
Sol:
for i in lt:
c=0
for j in i:
if j<=0: #Since 0 is neither positive nor negative
c=1
break
if c==0:
print(i,end=" ")
Output:
(3, 5, 9) (5, 7, 1)
Sol:
lt=[(1,2,3),(3,4,5),(5,6,7),(1,2,3),(5,6,7),(5,4,3)]
print("List of tuples after removing duplicates: ",list(set(lt)))
Output:
List of tuples after removing duplicates: [(3, 4, 5), (5, 4, 3), (5, 6
, 7), (1, 2, 3)]
5 Python program in which we need to perform Row-wise custom elements addition in Tuple
matrix
Sol:
lt=[[(0,1),(2,3)],[(4,5),(6,7)],[(8,9)]]
ce=['a','b','c']
count=0
for i in range(len(lt)):
for j in range(len(lt[i])):
lt[i][j]+=tuple(ce[count])
count+=1
print(lt)
Output:
19
[[(0, 1, 'a'), (2, 3, 'a')], [(4, 5, 'b'), (6, 7, 'b')], [(8, 9, 'c')]]
6 Python program to extract digits from Tuple list (I/p: [(1,3), (4,5] | o/p: [1,3,4,5]
Sol:
lt=[(1,3),(4,5)]
ans=[]
for i in lt:
for j in i:
if type(j)==int:
ans.append(j)
print(ans)
Output:
[1, 3, 4, 5]
Week - 9
1 Write a Python script to sort (ascending and descending) a dictionary by value.
Sol:
cars = {"BMW":4,"Lamborghini":3,"Aston Martin":1,"McLaren":5,"Bugati":2}
print("Dictionary elements in ascending order =",*sorted(cars.items(), key=lambda x:x[1]))
print("Dictionary elements in descending order =",*sorted(cars.items(),key=lambda
x:x[1],reverse = True))
Output:
Dictionary elements in ascending order = ('Aston Martin', 1) ('Bugati',
2) ('Lamborghini', 3) ('BMW', 4) ('McLaren', 5)
Dictionary elements in descending order = ('McLaren', 5) ('BMW', 4) ('L
amborghini', 3) ('Bugati', 2) ('Aston Martin', 1)
2 Write a Python program to convert string values of a given dictionary, into integer/float
datatypes.
Sol:
Output:
20
Dictionary values in float datatype = [{'BMW': 4.0, 'Lamborghini': 3.0,
'Aston Martin': 1.0, 'McLaren': 5.0, 'Bugati': 2.0}]
3 Given a list and dictionary, map each element of list with each item of dictionary, forming
nested dictionary as value.
Sol:
result = {}
for key, ele in zip(my_list, my_dict.items()):
result[key] = dict([ele])
Output:
4 Given a list, write a Python program to convert the given list to dictionary such that all the
odd elements have the key, and even number elements have the value. Since python
dictionary is unordered, the output can be in any order.
Sol:
my_list = ["One",1,"Two",2,"Three",3]
if len(my_list)%2==0:
result = {my_list[i]:my_list[i+1] for i in range(0,len(my_list),2)}
print(result)
else:
print("Dictionary cannot be formed with the given elements.")
Output:
Sol:
list1 = ["Rohit","Sachin","Kohli","Dhoni"]
list2 = [53,72,66,48]
print(dict(zip(list1,list2))) #zip() function pairs the list element with other list element at
corresponding index in form of key-value pairs.
21
Output:
Week – 10 & 11
11. Class with Public Attributes, Create a class named Person with the following 2 public
attributes.
name,age
Include a constructor .
__init__(self,name, age)
Create an object of class Person to test the above class.
Sample Input and Output:
[All text in bold corresponds to input and the rest corresponds to output]
Enter name
Mahirl
Enter age
10
Person Details
Mahirl
10
Solution:
Main.py
from Person import Person
p1=Person(str(input("Enter name\n")),int(input("Enter age\n")))
print("Person Details")
print(p1.name)
print(p1.age)
Person.py
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
Output:
22. Create a class named Person with the following 2 private attributes.
__name, __age
Include a constructor.
__init__(self,name, age)
22
Include a method
__str__(self)
This method returns a string corresponding to person details in the format specified in the
sample output.
Create an object of class Person to test the above class.
Note:
The __str__ method is useful for a string representation of the object, either when someone
codes in str(your_object), or even when someone might do print(your_object).
Input and Output Format:
Refer Sample Input and Output for formatting specifications.
[All text in bold corresponds to input and the rest corresponds to output]
Sample Input and Output:
Enter name
Mahirl
Enter age
10
Person Details
Mahirl is 10 years old
SOLUTION
Main.py
from Person import Person
p1=Person(str(input("Enter name\n")),int(input("Enter age\n")))
print("Person Details")
print(str(p1))
Person.py
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):
return self.name + ' is ' + str(self.age) + ' years old '
OUTPUT
23
This domain_name is used for generating the email id.
Include a constructor .
___init__(self,first_name, last_name,age)
email is formed by concatenating the first name, last name and with given domain name in
the format
specified in the output.
Include a method
__str__(self)
This method returns a string corresponding to person details in the format specified in the
sample output.
fullname(self)
This method returns the full name of the person as a concatenation of first name and last
name
separated by a space.
Create an object of class Person to test the above class.
Sample Input and Output:
[All text in bold corresponds to input and the rest corresponds to output]
3. Enter domain name
amphi@in
Enter details of first person
Enter first name
Mahirl
Enter last name
Malar
Enter age
10
Enter details of second person
Enter first name
Madhu
Enter last name
Kavi
Enter age
15
First Person Details
Full name of the person is Mahirl Malar
Mahirl Malar is 10 years old and her email id is Mahirl.Malar@amphi@in
Second Person Details
Full name of the person is Madhu Kavi
Madhu Kavi is 15 years old and her email id is Madhu.Kavi@amphi@in
SOLUTION
Main.py
from Person import Person
24
person_first_name = input("Enter first name\n")
person_last_name = input("Enter last name\n")
person_age = input("Enter age\n")
person1 = Person(person_first_name, person_last_name, person_age)
print("Enter details of second person")
person_first_name = input("Enter first name\n")
person_last_name = input("Enter last name\n")
person_age = input("Enter age\n")
person2 = Person(person_first_name, person_last_name, person_age)
print("First Person Details")
print("Full name of the person is " + person1.fullname())
print(person1)
print("Second Person Details")
print("Full name of the person is " + person2.fullname())
print(person2)
Person.py
class Person:
domain_name="@amphi@in"
def __init__(self,first_name,last_name,age):
self.first_name=first_name
self.last_name=last_name
self.age=age
def __str__(self):
return self.first_name + ' ' + self.last_name + ' is ' + str(self.age) + ' years old and her
email id is ' + self.first_name + '.' + self.last_name + '@' + Person.domain_name
def fullname(self):
return self.first_name + ' ' + self.last_name
OUTPUT
25
44. Create an abstract class named AbstractStall.
Include an abstract method named display()
Create a class named Stall (derived from AbstractStall) that includes 4 protected attributes
_name
_details
_cost
_owner_name
Include appropriate __init__ method.
Include a method named display() to display the details in the format specified in the output.
Create a class named ExecutiveStall(derived from AbstractStall) that includes one private
attributes
__number_of_TV_set
Include appropriate __init__ method.
Include a method named display() to display the details in the format specified in the output.
Create a class named PremiumStall(derived from AbstractStall) that includes one private
attribute
__number_of_projector
Include appropriate __init__ method.
Include a method named display() to display the details in the format specified in the output.
Create objects of the above classes and test the above classes.
Input and Output Format:
Refer Sample Input and Output for formatting specifications.
[All text in bold corresponds to input and the rest corresponds to output]
Sample Input and Output 1:
Stall Type
1.Stall
2.Executive Stall
3.Premium Stall
Enter your choice:
26
3
Enter the stall details in csv format
Ram Mahal,Prime Locality,10000,Raghu,4
Stall name : Ram Mahal
Details : Prime Locality
Cost : 10000
Owner : Raghu
Number of Projectors : 4
Sample Input and Output 2:
Stall Type
1.Stall
2.Executive Stall
3.Premium Stall
Enter your choice:
1
Enter the stall details in csv format
Ram Mahal,Prime Locality,10000,Raghu
Stall name : Ram Mahal
Details : Prime Locality
Cost : 10000
Owner : Raghu
Sample Input and Output 3:
Stall Type
1.Stall
2.Executive Stall
3.Premium Stall
Enter your choice:
2
Enter the stall details in csv format
Ram Mahal,Prime Locality,10000,Raghu,3
Stall name : Ram Mahal
Details : Prime Locality
Cost : 10000
Owner : Raghu
Number of TV Sets : 3
SOLUTION
Main.py
from AbstractStall import AbstractStall
from Stall import Stall
from ExecutiveStall import ExecutiveStall
from PremiumStall import PremiumStall
print("Stall Type")
print("1.Stall")
print("2.Executive Stall")
27
print("3.Premium Stall")
ch=(int)(input("Enter your choice:\n"))
if ch==1:
input_str = input("Enter the stall details in csv format\n")
name, details, cost, owner_name = input_str.split(",")
stall = Stall(name, details, cost, owner_name)
stall.display()
elif ch==2:
input_str = input("Enter the stall details in csv format\n")
name, details, cost, owner_name, notv = input_str.split(",")
es=ExecutiveStall(name, details, cost, owner_name, notv)
es.display()
elif ch==3:
input_str = input("Enter the stall details in csv format\n")
name, details, cost, owner_name, nopr = input_str.split(",")
ps=PremiumStall(name, details, cost, owner_name, nopr)
ps.display()
else:
print("Invalid Input")
PremiumStall.py
from AbstractStall import AbstractStall
class PremiumStall(AbstractStall):
def _init_(self,name,details,cost,owner_name,number_of_projector):
self._name=name
self._details=details
self._cost=cost
self._owner_name=owner_name
self.__number_of_projector=number_of_projector
def display(self):
print("Stall name : "+self._name)
print("Details : "+self._details)
print("Cost : "+self._cost)
print("Owner : "+self._owner_name)
print("Number of Projectors : "+self.__number_of_projector)
AbstractStall.py
import abc
from abc import ABC,abstractmethod
class AbstractStall(ABC):
@abstractmethod
def display(self):
pass
ExecutiveStall.py
28
from AbstractStall import AbstractStall
class ExecutiveStall(AbstractStall):
def _init_(self,name,details,cost,owner_name,number_of_TV_set):
self._name=name
self._details=details
self._cost=cost
self._owner_name=owner_name
self.__number_of_TV_set=number_of_TV_set
def display(self):
print("Stall name : "+self._name)
print("Details : "+self._details)
print("Cost : "+self._cost)
print("Owner : "+self._owner_name)
print("Number of TV Sets : "+self.__number_of_TV_set)
Stall.py
from AbstractStall import AbstractStall
class Stall(AbstractStall):
def _init_(self,name,details,cost,owner_name):
self._name=name
self._details=details
self._cost=cost
self._owner_name=owner_name
def display(self):
print("Stall name : "+self._name)
print("Details : "+self._details)
print("Cost : "+self._cost)
print("Owner : "+self._owner_name)
OUTPUT
29
Week – 12 & 13
1 Create a class named Employee with the following 3 protected attributes
_name
_pay
_email
Include a __init__ method to initialize the values.
Name and pay are passed as arguments. Email is formed by concatenating name
with .”@gmail.com”
Create a subclass named Developer (derived from Employee class) with 1 additional
attribute.
_Developer__prog_lang
Include appropriate __init__ method to initialize the values.
Create objects of the above classes and test them.
Note:
Objective of the problem is to illustrate the order in which the init methods are invoked while
creating objects and to display the class attributes in the Employee class and Developer class.
Input and Output Format:
Refer Sample Input and Output for formatting specifications.
[All text in bold corresponds to input and the rest corresponds to output]
Sample Input and Output:
Create an Employee Object
30
Enter Employee details in comma separated format
Mahirl,30
Inside Employee init method
Create a Developer object
Enter Developer details in comma separated format
Esha,34,40000
Inside Developer init method
Inside Employee init method
Employee Class Attributes
['_email', '_name', '_pay']
Developer Class Attributes
['_Developer__prog_lang', '_email', '_name', '_pay']
SOLUTION
Main.py
from Employee import Employee
from Developer import Developer
print("Create an Employee Object")
input_str = input("Enter Employee details in comma separated format\n")
name, pay = input_str.split(",")
employee = Employee(name, pay)
print("Create a Developer object")
input_str = input("Enter Developer details in comma separated format\n")
name, pay, prog_lang = input_str.split(",")
developer = Developer(name, pay, prog_lang)
print("Employee Class Attributes")
print(sorted(employee.__dict__))
print("Developer Class Attributes")
print(sorted(developer.__dict__))
Devoloper.py
from Employee import Employee
class Developer(Employee):
def __init__(self,name,pay,Developer__prog_lang):
print("Inside Developer init method")
self._name=name
self._pay=pay
self._email=name+"."+"@gmail.com"
self._Developer__prog_lang=Developer__prog_lang
Employee.__init__(self,name,pay)
Employee.py
class Employee:
def __init__(self,name,pay):
print("Inside Employee init method")
31
self._name=name
self._pay=pay
self._email=name+"."+"@gmail.com"
OUTPUT
5.
2 Create a class named Employee with the following 3 protected attributes
_name
_pay
_email
Include a __init__ method to initialize the values.
Name and pay are passed as arguments. Email is formed by concatenating name
with .”@gmail.com”
Include @property decorator for the attribute name.
Create a subclass named Developer (derived from the Employee class) with 1 additional
attribute.
_prog_lang
Include an appropriate __init__ method to initialize the values.
Create a subclass named Manager (derived from the Employee class) with 1 additional
attribute.
_employees
the employee is a list that contains the list of employees assigned to a manager.
Include an appropriate __init__ method to initialize the values.
In this method, set the default value of employees to None.
Inside the method, if the value of employees is None, initialize it to a []. (empty list)
Include addEmployee() and removeEmployee() methods.
Create another class named Utility. This class is normally used for adding all commonly used
methods.
Include a method named to return a list of employees under each manager.
Create objects of the above classes and test them.
The manager list is prepopulated. Assume that we are not going to add a new Managers in
32
this program.
Input and Output Format:
Refer Sample Input and Output for formatting specifications.
[All text in bold corresponds to input and the rest corresponds to output]
Sample Input and Output:
Menu
1)Employee
2)Developer
Enter choice
1
Enter Employee details in comma separated format
Esha,20000
Enter manager name
Arun
Do you want to continue? Type yes/no
yes
Menu
1)Employee
2)Developer
Enter choice
2
Enter Developer details in comma separated format
Fathima,30000,Java
Enter manager name
Deva
Do you want to continue? Type yes/no
yes
Menu
1)Employee
2)Developer
Enter choice
2
Enter Developer details in comma separated format
Geetha,28000,Java
Enter manager name
Arun
Do you want to continue? Type yes/no
no
Manager and Employee Allocation List
Manager Name :Arun
Employee List :
Esha Geetha
Manager Name :Babu
Employee List :
None
Manager Name :Chandru
33
Employee List :
None
Manager Name :Deva
Employee List :
Fathima
SOLUTION
Main.py
from Employee import Employee
from Developer import Developer
from Manager import Manager
from Utility import Utility
manager_list = []
manager_list.append(Manager("Arun",80000))
manager_list.append(Manager("Babu",100000))
manager_list.append(Manager("Chandru",60000))
manager_list.append(Manager("Deva",60000))
input_obj_list = []
choice = "yes"
while choice=="yes" :
print("Menu\n1)Employee\n2)Developer\n")
choice1 = input("Enter choice\n")
if choice1 == "1" :
input_str = input("Enter Employee details in comma separated format\n")
name, pay = input_str.split(",")
employee = Employee(name, pay)
input_obj_list.append(employee)
mgr_name = input("Enter manager name\n")
for manager in manager_list :
if manager.name == mgr_name :
manager.add_employee(employee)
else :
input_str = input("Enter Developer details in comma separated format\n")
name, pay, prog_lang = input_str.split(",")
developer = Developer(name, pay, prog_lang)
input_obj_list.append(developer)
mgr_name = input("Enter manager name\n")
for manager in manager_list :
if manager.name == mgr_name :
manager.add_employee(developer)
choice = input("Do you want to continue? Type yes/no\n")
34
print("\nManager and Employee Allocation List")
Utility.print_employees_under_each_manager(manager_list)
print("\n")
Devoloper.py
from Employee import Employee
class Developer(Employee):
def __init__(self,name,pay,prog_lang) :
self._prog_lang=prog_lang
super().__init__(name,pay)
def _str_(self) :
return self._name
Utility.py
from Employee import Employee
from Developer import Developer
from Manager import Manager
class Utility :
@staticmethod
def print_employees_under_each_manager(manager_list) :
for i in manager_list:
print("Manager Name :",i._name)
print("Employee List :")
j=None
for j in range(len(i._employees)):
print(i._employees[j]._name,end=" ")
if(j==None):
print("None")
print()
print()
Employee.py
class Employee:
def __init__(self,name,pay):
self._name=name
self._pay=pay
self._email=self._name+".@gmail.com"
@property
def name(self):
return self._name
@name.setter
def name(self,val):
self._name=val
def _str_(self) :
return self._name
35
Manager.py
from Employee import Employee
class Manager(Employee):
def __init__(self,name,pay,employees=None):
if(employees==None):
self._employees=[]
super().__init__(name,pay)
def add_employee(self,emp):
self._employees.append(emp)
def remove_employee(self,emp):
self._employees.remove(emp)
OUTPUT
36
Week – 14
1 Write a Python program that accepts two numbers as input (say x and y) and finds x/y.
When the denominator is 0, the program should raise a ZeroDivisionError Exception and
print the message shown in the sample output.
Input Format:
Input consists of 2 integers
Output Format:
Output is either the result or the error message.
Refer sample output.
[All text in bold corresponds to input and the rest corresponds to output]
Sample Input and Output 1:
Enter number 1
6
Enter number 2
3
2.0
Sample Input and Output 2:
Enter number 1
5
Enter number 2
0
Divide By Zero Error
SOLUTION
37
a=int(input("Enter number1\n"))
b=int(input("Enter number2\n"))
try:
c=a/b
except ZeroDivisionError:
print("Division by Zero Error")
OUTPUT
2 An input list is given in the code template. Write a program to find the sum of first n values
from the given list. For invalid ‘n’ values, raise an IndexError Exception and display the
message shown in the sample output
SOLUTION
numlist=[2,3,1,5,6,7,1]
print(numlist)
try:
n=int(input("Enter n\n"))
s=0
for i in range(0,n,1):
s+=numlist[i]
except IndexError:
print("Index Value out of range")
else:
print("Sum = {}".format(s))
OUTPUT
38
3 Create a class named Student with a single attribute – marks.
Include a method named check_marks in the Student Class.
This method checks whether the marks is greater than or equal to 90 and if it is greater than
or equal to 90, the method returns True. If the marks is less than 90, a custom Exception
named NotEligibleException is raised and an appropriate message as shown in the sample
output is displayed. Create a custom Exception class named NotEligibleException. Create an
object of the student class and test the above methods.
SOLUTION
class NotEligibleException(Exception):
pass
class Student:
def __init__(self,marks):
self.marks=marks
def check_marks(self):
if self.marks>=90:
return True
else:
raise NotEligibleException("Inside Except Block : Not Eligible")
print("Enter marks of student")
try:
n=int(input())
s=Student(n)
s.check_marks()
except NotEligibleException as nee:
print(nee)
else:
print("Eligible")
OUTPUT
39
4 Write a Python to count the number of persons inside a bank, by increasing count whenever a
person enters a bank, using an increment(++) operator overloading function, and decrease the
count whenever a person leaves the bank using a decrement(--) operator overloading function
inside a class.
Solution:
class myint_plus:
def __init__(self,myint_instance):
self.myint_instance = myint_instance
def __pos__(self):
self.myint_instance.i += 1
return self.myint_instance
class myint:
def __init__(self,i):
self.i = i
def __pos__(self):
return myint_plus(self)
def __repr__(self):
return self.i.__repr__()
x = myint(1)
print(x)
++x
print(x)
Similarly for (--) operator
Output:
40
List of Viva Questions:
41
32. Explain inheritance in Python with an example
33. What is polymorphism in Python?
34. What is the ternary operator?
35. What are global and local variables in Python?
36. How is try/except used in Python?
37. Explain the differences between Python 2 and Python 3
38. What is the join method in python?
39. What is dictionary?
40. How would you check if a key exists in a Python dictionary?
41. How would you sort a dictionary in Python?
42. What is a Python Docstring?
43. What are Python modules?
44. Does converting an object to a set maintain the object’s order?
45. Check if a set is a subset of another set
46. Is a set a subset of itself?
47. What is the difference between a subset and a proper subset?
48. How to find the union of 2 sets.
49. Can you zip 2 sets together?
50. Can a set be accessed by index?
51. What is the difference between a set and a tuple?
52. What is the difference between a set and a frozenset?
53. What are the key features of Python?
54. What type of language is python? Programming or scripting?
55. How is memory managed in Python?
56. What is namespace in Python?
57. Is python case sensitive?
58. What is type conversion in Python?
59. What are functions in Python?
60. How does break, continue and pass work?
61. What are python iterators?
62. Which module is used to generate random numbers?
63. How do you write comments in python?
64. How will you capitalize the first letter of string? What does an object() do?
65. How to comment multiple lines in python?
66. What are docstrings in Python?
67. What is the purpose of is, not and in operators?
68. What does len() do?
69. Explain split(), sub(), subn() methods of “re” module in Python.
70. What are negative indexes and why are they used?
71. What are Python packages?
42
72. What are the built-in types of python?
73. What are Python libraries? Name a few of them.
74. How to import modules in python?
75. Does python support multiple inheritance?
-
Program Coordinator -
Head of the
Dr. A RATNAKAR
Department
HOD-CSE HOD-IT
43