Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
41 views150 pages

OOP Lab Workbook Guide

Uploaded by

vvsudarsan.16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views150 pages

OOP Lab Workbook Guide

Uploaded by

vvsudarsan.16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 150

23CS1207- Object Oriented Programming

LABORATORY WORKBOOK

Name of the Student:

Register Number:

Year:
FIRST
Semester:
EVEN
Section:

Name of the Faculty:

1
23CS1207- Object Oriented Programming
INDEX

Remarks
Exp.No Date Title of the
Programs &
Signature
1

10

11

12

Faculty In-charge Course Coordinator HOD (BES-1)

2
23CS1207- Object Oriented Programming

Table of contents

Lab Page
Contents
Exercise Number
Organization of Students Lab Workbook 5
Start
Lab Continuous Evaluation Plan 6
Prerequisite for Lab-1 10
Pre-Lab Task 10

Lab -1 In- Lab Task 11


Post- Lab Task 14
Skill Session 16
Prerequisite for Lab-2 20
Pre-Lab Task 20
Lab -2 In- Lab Task 21
Post- Lab Task 24
Skill Session 26
Prerequisite for Lab-3 30
Pre-Lab Task 30
Lab -3 In- Lab Task 31
Post- Lab Task 34
Skill Session 36
Prerequisite for Lab-4 41
Pre-Lab Task 41

Lab -4 In- Lab Task 42


Post- Lab Task 45
Skill Session 47

Prerequisite for Lab-5 51

Pre-Lab Task 51
Lab -5 In- Lab Task 52
Post- Lab Task 55
Skill Session 57
Prerequisite for Lab-6 61
Pre-Lab Task 61
Lab -6 In- Lab Task 62
Post- Lab Task 65
Skill Session 67

3
23CS1207- Object Oriented Programming

Prerequisite for Lab-7 72


Pre-Lab Task 72
Lab -7 In- Lab Task 73
Post- Lab Task 76
Skill Session 79
Prerequisite for Lab-8 83
Pre-Lab Task 83
Lab -8 In- Lab Task 84
Post- Lab Task 87
Skill Session 89
Prerequisite for Lab-9 93
Pre-Lab Task 93
Lab -9 In- Lab Task 94
Post- Lab Task 97
Skill Session 99
Prerequisite for Lab-10 101
Pre-Lab Task 101
Lab -10
In- Lab Task 102
Post- Lab Task 105
Skill Session 107
Prerequisite for Lab-11 110
Pre-Lab Task 110
Lab -11 In- Lab Task 111
Post- Lab Task 114
Skill Session 116
Prerequisite for Lab-12 120
Pre-Lab Task 120
Lab -12 In- Lab Task 121
Post- Lab Task 124
Skill Session 126

4
23CS1207- Object Oriented Programming

Organization of the STUDENTS LAB WORKBOOK

The laboratory framework includes a creative element but shifts the time-intensive aspects
outside of the Two-Hour closed laboratory period. Within this structure, each laboratory
includes three parts: Pre-lab, In-lab, and Post-lab.

a. Pre-Lab

The Pre-lab exercise is a homework assignment that links the lecture with the laboratory period
- typically takes 2 hours to complete. The goal is to synthesize the information they learn in
lecture with material from their textbook to produce a working piece of software. Pre-lab
Students attending a two-hour closed laboratory are expected to make a good-faith effort to
complete the Pre-lab exercise before coming to the lab. Their work need not be perfect, but
their effort must be real (roughly 80 percent correct).

b. In-Lab

The In-lab section takes place during the actual laboratory period. The First hour of the
laboratory period can be used to resolve any problems the students might have experienced in
completing the Pre-lab exercises. The intent is to give constructive feedback so that students
leave the lab with working Pre-lab software - a significant accomplishment on their part.
During the second hour, students complete the In-lab exercise to reinforce the concepts
learned in the Pre-lab. Students leave the lab having received feedback on their Pre-lab and In-
lab work.

c. Post-Lab

The last phase of each laboratory is a homework assignment that is done following the
laboratory period. In the Post-lab, students analyze the efficiency or utility of a given system
call. Each Post-lab exercise should take roughly 120 minutes to complete.

5
23CS1207- Object Oriented Programming

2023-24 EVEN SEMESTER LAB CONTINUOUS EVALUATION

Pre-Lab In-Lab(30M)
S. (15M) Viva Total Faculty
No Date Experiment Name Voce (50M) Signature
Logic Impleme Executi Logic Execution Result Analysis
ntation (5M) (5M) (5M)
(5M) on(5M) (10M) (10M)
(5M)

8
23CS1207- Object Oriented Programming

2023-24 EVEN SEMESTER LAB CONTINUOUS EVALUATION

Pre-Lab
In-Lab(30M) Viva
S. (15M) Total Faculty
No Date Experiment Name Voce (50M) Signature
Logic Impleme Executi Logic Execution Result Analysis
ntation (5M) (5M) (5M)
(5M) on(5M) (10M) (10M)
(5M)

10

11

12

Faculty In-Charge Course Coordinator HOD (BES-I)


23CS1207- Object Oriented Programming

2023-24 EVEN SEMESTER SKILL CONTINUOUS EVALUATION

Skill Session(50M)
Sl Total Faculty Signature
No Date Experiment Name LOGIC EXECUTION RESULT ANALYSIS (50M)
(20M) (10M) (10M) (10M)

8
23CS1207- Object Oriented Programming

2023-24 EVEN SEMESTER SKILL CONTINUOUS EVALUATION

Skill Session(50M)
Sl Total Faculty Signature
No Date Experiment LOGIC EXECUTION RESULT ANALYSIS (50M)
Name (20M) (10M) (10M) (10M)

10

11

12

Faculty In-Charge Course Coordinator HOD (BES-I)


23CS1207- Object Oriented Programming

WEEK - 1
Lab Session:

Date of the Session: / / Time of the Session: to

Prerequisite:

 Introduction to Python
 Data Types
 Boolean values and operators,
 operator precedence
and comments
 variables, expressions,
statements

Pre-lab Task:

1. What is Python? List some popular applications of Python in the world of technology.

2. How does Python differ from other programming languages?

3. What are the basic data types in Python, and how are they used in programming?

4. List various reserve words in Python?

10
23CS1207- Object Oriented Programming

In-lab Task:
1. Say "Hello, World!" With Python
Input Format
You do not need to read any input in this challenge.

Output Format
Print Hello, World! to stdout.

Sample Output
Hello, World

Link: https://www.hackerrank.com/challenges/py-hello-world/problem

Program:

11
23CS1207- Object Oriented Programming

2 Input Format
The first line contains the first integer.
The second line contains the second integer.
Constraints

Output Format
Print the three lines as explained above.

Sample Input
3
2
Sample Output
5
1
6

LINK: https://www.hackerrank.com/challenges/python-arithmetic-operators/problem

Program:

12
23CS1207- Object Oriented Programming

3. Python: Division
Input Format
The first line contains the first integer.
The second line contains the second integer.
Output Format
Print the two lines as described above.
Sample Input
4
3
Sample Output
1
1.33333333333

Link: https://www.hackerrank.com/challenges/python-division/problem

Program:

13
23CS1207- Object Oriented Programming

Post-lab Task:

1. Display “My Name Is James” as “My**Name**Is**James” using output formatting of a print()


function

Expected Output:

Use print() statement formatting to display ** separator between each word.

For example: print('My', 'Name', 'Is', 'James') will display MyNameIsJames

So use one of the formatting argument of print() to turn the output into My**Name**Is**James

Program:

14
23CS1207- Object Oriented Programming

2. The Display float number with 2 decimal places using print()

Expected Output:
Display 458.541315 as 458.54

Program:

15
23CS1207- Object Oriented Programming

Skill Session:

1. For Maximum Edge of a Triangle


Create a function that finds the maximum range of a triangle's third edge, where the side lengths are all
integers.

Examples
next_edge(8, 10) ➞
17

next_edge(5, 7) ➞ 11

next_edge(9, 2) ➞ 10

Notes
(side1 + side2) - 1 = maximum range of third edge.
The side lengths of the triangle are positive integers

Program:

16
23CS1207- Object Oriented Programming

2. Complete the exercise problems given in the link provided

https://holypython.com/beginner-python-exercises/exercise-2-python-variables/

Program:

17
23CS1207- Object Oriented Programming

3. Complete the exercise problems given in the link provided

https://holypython.com/beginner-python-exercises/exercise-3-python-data-types/

Program:

18
23CS1207- Object Oriented Programming

4. Return the Next Number from the Integer Passed


Create a function that takes a number as an argument, increments the number by 1 and returns the
result.
Examples
addition(0) ➞ 1
addition(9) ➞ 10
addition(-3) ➞ -2

Program:

19
23CS1207- Object Oriented Programming

WEEK - 2

Lab Session:

Date of the Session: / / Time of the Session: to


Prerequisite:

 Conditional Statements
 Operators

Pre-lab Task:

1. What are the different types of operators in Python?

2. What are bitwise operators in Python?

3. Write the syntax of simple if statement?

4. Is there any limit of statement that can appear under an if block?

5. What is the output of the following


code? x = 6
y=2
print(x**y)
print(x//y)

20
23CS1207- Object Oriented Programming

In-lab Task:

1. (Physics: Find runway length) Given an airplane‟s acceleration a and take-off-speed v, you
can compute the minimum runway length needed for an airplane to take off using the
following formula:
Write a program that prompts the user to enter v in meters/second (m/s) and the acceleration
a in meters/second squared(m/s2),and displays the minimum runway length. Here is a sample
run: length =v2/2a
Enter speed and acceleration: 60, 3.5
The minimum runway length for this airplane is 514.286 meters

Program:

v=float(input("enter the value"))


a=float(input("enter the value"))
lenth=(v*v)/(2*a)
print("%.3f"%lenth)

21
23CS1207- Object Oriented Programming

2. (Find the number of days in a month) Write a program that prompts the user to enter the month and
year and displays the number of days in the month. For example, if the user entered month 2 and year
2000, the program should display that February 2000 has 29 days. If the user entered month 3 and
year 2005, the program should display that March 2005 has 31 days.

Program:
def is_leap_year(year):
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

def num_days_in_month(month, year):


if month == 2:
if is_leap_year(year):
return 29
else:
return 28
elif month in [4, 6, 9, 11]:
return 30
else:
return 31

def main():
month = int(input("Enter the month (1-12): "))
year = int(input("Enter the year: "))

days = num_days_in_month(month, year)

if month == 2:
month_name = "February"
elif month == 3:
month_name = "March"
elif month == 4:
month_name = "April"
elif month == 5:
month_name = "May"
elif month == 6:
month_name = "June"
elif month == 7:
month_name = "July"
elif month == 8:
month_name = "August"
elif month == 9:
month_name = "September"
elif month == 10:
month_name = "October"
elif month == 11:
month_name = "November"
elif month == 12:
month_name = "December"
else:
month_name = "January"

print(f"{month_name} {year} has {days} days.")

if __name__ == "__main__":
main()

22
23CS1207- Object Oriented Programming

or

def display(month,year):
days=[0,31,28,31,30,30,31,30,31,30,31]
if year%4==0 and month==2:
days[month]=28+1
print(year,month,days[month])
else:
print(year,month,days[month])
a=int(input("enter the value"))
b=int(input("enter the value"))
display(a,b)

23
23CS1207- Object Oriented Programming

3. Given 3 integers A, B, C. Do the following steps-


1. Swap A and B.
2. Multiply A by C.
3. Add C to B.
Output new values of A and B.
Sample Input
13 5 2
Sample Output
10 15

Program:

24
23CS1207- Object Oriented Programming

Post-lab Task:

1. Write a function that returns the maximum of two numbers.

Program:

def max_of_two(a, b):


if a > b:
return a
else:
return b

# Example usage:
num1 = 10
num2 = 20
print("The maximum of", num1, "and", num2, "is:", max_of_two(num1, num2))

25
23CS1207- Object Oriented Programming

2. Write a function called (fizzbuzz) that takes a number. If the number is divisible by 3, it should
return “Fizz”. If it is divisible by 5, it should return “Buzz”. If it is divisible by both 3 and 5, it
should return “FizzBuzz”. Otherwise, it should return the same number.

Program:

def fizzbuzz(number):
if number % 3 == 0 and number % 5 == 0:
return "FizzBuzz"
elif number % 3 == 0:
return "Fizz"
elif number % 5 == 0:
return "Buzz"
else:
return number

num=int(input(“enter num”))
print(fizzbuzz(num))

26
23CS1207- Object Oriented Programming

Skill Session:

1. Write a function for checking the speed of drivers. This function should have one parameter:
speed.
If speed is less than 70, it should print “Ok”.
Otherwise, for every 5km above the speed limit (70), it should give the driver one demerit point
and print the total number of demerit points. For example, if the speed is 80, it should print:
“Points: 2”.
If the driver gets more than 12 points, the function should print: “License suspended”

Program:

def check_speed(speed):
speed_limit = 70
demerit_points = 0

if speed <= speed_limit:


print("Ok")
else:
demerit_points = (speed - speed_limit) // 5
if demerit_points <= 12:
print(f"Points: {demerit_points}")
else:
print("License suspended")

num=int(input(“enter num”))

check_speed(num)

27
23CS1207- Object Oriented Programming

2. Given a two integer numbers return their product and if the product is greater than 1000, then
return their sum.

Program:
def calculate_product_or_sum(num1, num2):
product = num1 * num2
if product > 1000:
return num1 + num2
else:
return product
num=int(input(“enter num1”))
num=int(input(“enter num2”))
result1 = calculate_product_or_sum(20, 30)

28
23CS1207- Object Oriented Programming

3. Football Points
Create a function that takes the number of wins, draws and losses and calculates the number of
points a football team has obtained so far.
Wins get 3 points
Draws get 1 point
Losses get 0 points

Examples
Football points (3, 4, 2) ➞ 13
Football points (5, 0, 2) ➞ 15
Football points (0, 0, 1) ➞ 0
Note:
Inputs will be numbers greater than or equal to 0

Link: https://edabit.com/challenge/gwqqc5p3oiFXRJAQm

Program:
def calculate_points(wins, draws, losses):
total_points = (wins * 3) + (draws * 1)
return total_points

wins=int(input(“enter num1”))
draws=int(input(“enter num2”))
loss=int(input(“enter num2”))

total_points = calculate_points(wins, draws, loss)

29
23CS1207- Object Oriented Programming

4. Maximum Difference
Given a list of integers, return the difference between the largest and smallest integers in the list.
Examples
difference([10, 15, 20, 2, 10, 6]) ➞ 18
# 20 - 2 = 18

difference([-3, 4, -9, -1, -2, 15]) ➞ 24


# 15 - (-9) = 24

difference([4, 17, 12, 2, 10, 2]) ➞ 15

Program: def difference(numbers):


if not numbers:
return 0 # Return 0 if the list is empty
else:
return max(numbers) - min(numbers)

# Example usage:
result = difference([10, 15, 20, 2, 10, 6])
print("Difference:", result)

30
23CS1207- Object Oriented Programming

31
23CS1207- Object Oriented Programming

WEEK - 3

Lab Session:

Date of the Session: / / Time of the Session: to

Prerequisite:

 Loops

 List

Pre-lab Task:

1. What is the purpose of a loop in Python?

2. Which keyword is used to exit a loop in Python?

3. What is the output of the following code in python?


for i in range(3):
print(i)

4. What is the purpose of the list in Python?

5. In python, List is mutable

32
23CS1207- Object Oriented Programming

In-lab Task:

1. Input Format
The first and only line contains the integer, n
Constraints

Output Format
Print lines, one corresponding to each i
Sample Input
5
Sample Output
0
1
4
9
16
https://www.hackerrank.com/challenges/python-loops/problem

Program:

33
23CS1207- Object Oriented Programming

2. (Display two patterns using loops) Use nested loops that display the following
Patterns in four separate programs:

Program:
i.
for i in range(1, 6, 1):

for j in range(i):
print(j, end=" ")
print()
ii
for i in range(6, 0, -1):

for j in range(i):
print(j, end=" ")
print()

34
23CS1207- Object Oriented Programming

3. Given a Python list. Turn every item of a list into its square a List = [1, 2, 3, 4, 5, 6, 7]
Expected output:
[1, 4, 9, 16, 25, 36, 49]

Program:

List = [1, 2, 3, 4, 5, 6, 7]
squared_list = [x ** 2 for x in List]
print(squared_list)

35
23CS1207- Object Oriented Programming

Post-lab Task:

1. Given a two Python list. Iterate both lists simultaneously such that list1 should display item in
original order and list2 in reverse order
list1 = [10, 20, 30, 40]
list2 = [100, 200, 300, 400]
Expected output:
10 400
20 300
30 200
40 100

Program:

list1 = [10, 20, 30, 40]


list2 = [100, 200, 300, 400]
for item1, item2 in zip(list1, reversed(list2)):
print(item1, item2)

or
list1 = [10, 20, 30, 40]
list2 = [100, 200, 300, 400]
n = len(list2)
for i in range(len(list1)):
print(list1[i], list2[n - i - 1])

36
23CS1207- Object Oriented Programming

2. Accept list of 5 float numbers as an input from user

Expected output:
Numbers can be any
[78.6, 78.6, 85.3, 1.2, 3.5]

Program:
number_list = []
n = int(input("Enter the list size "))

print("\n")
for i in range(0, n):
print("Enter number at index", i, )
item = float(input())
number_list.append(item)
print("User list is ", number_list)

37
23CS1207- Object Oriented Programming

Skill Session:

1. Remove empty strings from the list of strings


list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]
Expected output:
["Mike", "Emma", "Kelly", "Brad"]

Program:
list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]

# Remove empty strings using list comprehension


filtered_list = [x for x in list1 if x]

print(filtered_list)

or
list1 = ["Mike", "", "Emma", "Kelly", "", "Brad”]
filtered_list = []
for x in list1:
if x:
filtered_list.append(x)

print(filtered_list)

38
23CS1207- Object Oriented Programming

2. Print the following pattern using for loop


54321
4321
321
21
1
Program:
for i in range(5, 0, -1):
for j in range(i, 0, -1):
print(j, end=" ")
print()

39
23CS1207- Object Oriented Programming

3. (Use the math.sqrt() function) Write a program that prints the following table
using the sqrt() function in the m ath module.

Number Square Root


0 0.0000
2 1.4142
18 5.2426
20 5.4721

Program:
import math

print("Number\tSquare Root")

for num in range(1, 11):


square_root = math.sqrt(num)

# Print the number and its square root, formatted nicely


print(f"{num}\t{square_root:.4f}")

40
23CS1207- Object Oriented Programming

4. Given a nested list extend it with adding sub list ["h", "i", "j"] in a such a way that it will look like
the following list

Given List:
list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
Sub List to be added = ["h", "i", "j"]

Expected output:

['a', 'b', ['c', ['d', 'e', ['f', 'g', 'h', 'i', 'j'], 'k'], 'l'], 'm', 'n']

Program:

list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
sublist = ["h", "i", "j"]

list1[2][1][2].extend(sublist)

print(list1)

41
23CS1207- Object Oriented Programming

5. Accept number from user and calculate the sum of all number between 1 and given number For
example user given 10 so the output should be 55

Program:
num = int(input("Enter a number: "))
sum_of_numbers = 0
for i in range(1, num + 1):
sum_of_numbers +=
print("The sum of all numbers from 1 to", num, "is:", sum_of_numbers)

42
23CS1207- Object Oriented Programming

43
23CS1207- Object Oriented Programming

WEEK - 4

Lab Session:

Date of the Session: / / Time of the Session: to


Prerequisite:

 Lists comprehension
 Tuple
 Set, Dictionary

Pre-lab Task:

1. Difference between list comprehension & for loop in Python?

2. Advantages of list comprehension?

3. How to Add and Remove Elements from a Set??

4. Write the output of the following code?


T1 = (45,67,98)
T1 = T1 + (1,2,3)
print(T1)

5. Difference between dictionary & set in Python

44
23CS1207- Object Oriented Programming

In-lab Task:

1. Input Format
Four integers x, y, z and ,n each on a separate line.
Constraints
Print the list in lexicographic increasing order.
Sample Input
1
1
1
2
Sample Output
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]

https://www.hackerrank.com/challenges/list-comprehensions/problem

Program: list comprehension

if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())

ls = [[i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if i+j+k != n]


print(ls)

or

if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
l = []
for i in range(x+1):
for j in range(y+1):
for k in range(z+1):
if i+j+k == n:
continue
l.append([i,j,k])
print(l)

45
23CS1207- Object Oriented Programming

2. Concatenate two lists in the following order


list1 = ["Hello ", "take "]
list2 = ["Dear", "Sir"]
Expected output:
['Hello Dear', 'Hello Sir', 'take Dear', 'take Sir']

Program:

46
23CS1207- Object Oriented Programming

3. Input Format
The first line contains an integer,n denoting the number of commands.
Each line i of the n subsequent lines contains one of the commands described above.
Constraints
The elements added to the list must be integers.
Output Format
For each command of type print, print the list on a new line.
Sample Input
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print pop
reverse
print
Sample Output 0
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]

https://www.hackerrank.com/challenges/python-lists/problem

Program:
if __name__ == '__main__':

N = int(input())

L=[];

for i in range(0,N):

cmd=input().split();

if cmd[0] == "insert":

L.insert(int(cmd[1]),int(cmd[2]))

elif cmd[0] == "append":

L.append(int(cmd[1]))

elif cmd[0] == "pop":

47
23CS1207- Object Oriented Programming

L.pop();

elif cmd[0] == "print":

print(L)

elif cmd[0] == "remove":

L.remove(int(cmd[1]))

elif cmd[0] == "sort":

L.sort();

else:

L.reverse();

48
23CS1207- Object Oriented Programming

Post-lab Task:

1. Determines whether or not the following two sets have any elements in common. If yes display
the common elements
set1 = {10, 20, 30, 40, 50}
set2 = {60, 70, 80, 90, 10}
Expected output:
Two sets have items in common
{10}

Program

49
23CS1207- Object Oriented Programming

2. Remove items from set1 that are not common to both set1 and set2
set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}

Program

50
23CS1207- Object Oriented Programming

Skill Session:

1. Blocks of Stock. A block of stock as a number of attributes, including a purchase date, a purchase
price, a number of shares, and a ticker symbol. We can record these pieces of information in
a tuple for each block of stock and do a number of simple operations on the blocks.
Let's dream that we have the following portfolio.
Purchase
Purchase Price Shares Symbol Current Price
Date
25 Jan 2001 43.50 25 CAT 92.45
25 Jan 2001 42.80 50 DD 51.19
25 Jan 2001 42.10 75 EK 34.87
25 Jan 2001 37.58 100 GM 37.58
We can represent each block of stock as a 5-tuple with purchase date, purchase price, shares, ticker
symbol and current price.
portfolio= [ ( "25-Jan-2001", 43.50, 25, 'CAT', 92.45 ),
( "25-Jan-2001", 42.80, 50, 'DD', 51.19 ),
( "25-Jan-2001", 42.10, 75, 'EK', 34.87 ),
( "25-Jan-2001", 37.58, 100, 'GM', 37.58 )]
(i)Determines the total purchase price of the portfolio.
(ii)Determine the total amount gained or lost.

https://www.linuxtopia.org/online_books/programming_books/python_programming/python_ch13s07.html

Program:

portfolio = [
("25-Jan-2001", 43.50, 25, 'CAT', 92.45),
("25-Jan-2001", 42.80, 50, 'DD', 51.19),
("25-Jan-2001", 42.10, 75, 'EK', 34.87),
("25-Jan-2001", 37.58, 100, 'GM', 37.58)
]

# Calculate total purchase price


total_purchase_price = sum(purchase_price * shares for _, purchase_price, shares, _, _ in portfolio)

# Calculate total current value


total_current_value = sum(current_price * shares for _, _, shares, _, current_price in portfolio)

# Calculate total amount gained or lost


total_gain_loss = total_current_value - total_purchase_price

print("Total Purchase Price of the Portfolio:", total_purchase_price)


print("Total Amount Gained or Lost:", total_gain_loss)

51
23CS1207- Object Oriented Programming

2. Create a new dictionary by extracting the following keys from a given dictionary
Given dictionary:
sampleDict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york"

}
Keys to extract

keys = ["name", "salary"]

Expected output:

{'name': 'Kelly', 'salary': 8000}

Program:
sampleDict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york"

}
keys=['name','age']
d={x:sampleDict[x] for x in keys}
print(d)

52
23CS1207- Object Oriented Programming

3. Delete set of keys from Python Dictionary


Given:
sampleDict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york"

}
keysToRemove = ["name", "salary"]
Expected output:
{'city': 'New york', 'age': 25}

Program:
sampleDict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york"

}
keys=['name','age']
d={x:sampleDict[x] for x in keys}
print(d)

53
23CS1207- Object Oriented Programming

4. Swap the following two tuples


tuple1 = (11, 22)
tuple2 = (99, 88)
Expected output:
tuple1 = (99, 88)
tuple2 = (11, 22)

Program: tuple1 = (11, 22)


tuple2 = (99, 88)
tuple1, tuple2 = tuple2, tuple1
print(tuple2)
print(tuple1)

54
23CS1207- Object Oriented Programming

55
23CS1207- Object Oriented Programming

WEEK - 5

Lab Session:

Date of the Session: / / Time of the Session: to


Prerequisite:

 Functions
 Strings

Pre-lab Task:

1. What is string in python?

2. Write the output of the following code


str = “Hello”
print(str[:3])

3. What is the output of the following function call


def fun1(name, age=20):
print(name, age)
fun1('Emma', 25)

4. What do you mean by traversing in string?

5. What is the output of the add() function call


def add(a, b):
return a+5, b+5
result = add(3, 2)
print(result)

56
23CS1207- Object Oriented Programming

In-lab Task:
1. Write a function
Input Format
Read , the year to test.
Constraints

Output Format
The function must return a Boolean value (True/False). Output is handled by the provided code
stub.
Sample Input
1990
Sample Output
False
Explanation
1990 is not a multiple of 4 hence it's not a leap year

Program:

defleep(n):
if n%4==0 or n%100==0 or n%400==0:
return True
else:
return False
n=int(input("enter the values"))
print(leep(n))

57
23CS1207- Object Oriented Programming

2. (Financial application: compute the future investment value) Write a function that computes a
future investment value at a given interest rate for a specified number of years. The future
investment is determined using the formula in Exercise 2.19.
Use the following function header:

deffutureInvestmentValue( investmentAmount, monthlyInterestRate, years):

For example, futureInvestmentValue(10000, 0.05/12, 5) returns 12833.59.


Write a test program that prompts the user to enter the investment amount and the annual
interest rate in percent and prints a table that displays the future value for
the years from 1 to 30. Here is a sample run:

The amount invested:1000


Annual interest rate:9
Years Future Value
1 1093.80
2 1196.41
29 13467.25
30 14730.57

Program:

def interest(p,r,t):
i=(p*t*r)/100
total=i+p
return total
p,r,t=map(float,input('enter the value %.2f').split())
print(interest(p,r,t))

print("The value of number till 2 decimal place(using %) is : ", end="")


print('the value %.2f' % a)

58
23CS1207- Object Oriented Programming

3. Write a Python function that prints out the first n rows of Pascal's triangle.

Note : Pascal's triangle is an arithmetic and geometric figure first imagined by Blaise Pascal.
Sample Pascal's triangle :

Each number is the two numbers above it added together.

Program:

def print_pascals_triangle(n):
for i in range(n):
# Print leading spaces for formatting
print(" " * (n - i - 1), end="")

# Initialize first value of each row


val = 1

# Print each value in the row


for j in range(i + 1):
print(val, end=" ")
val = val * (i - j) // (j + 1)

# Move to the next line for the next row


print()

# Example usage:
n = int(input("Enter the number of rows for Pascal's triangle: "))
print_pascals_triangle(n)

59
23CS1207- Object Oriented Programming

Post-lab Task:

1. Write a function func1() such that it can accept a variable length of argument and print all
arguments value
func1(20, 40, 60)
func1(80, 100)
Expected Output:

After func1(20, 40, 60):


20
40
60
After func1(80, 100):
80
100

Program:
def func1(*args):
print(*args)
func1('hello', 'hi', 23, '2383')

60
23CS1207- Object Oriented Programming

2. Write a function calculation() such that it can accept two variables and calculate the addition
and subtraction of it. And also it must return both addition and subtraction in a single return call
For example:

Program:

def calculation(a, b):


addition = a + b
subtraction = a - b
return addition, subtraction

# Example usage:
result_addition, result_subtraction = calculation(5, 3)
print("Addition result:", result_addition)
print("Subtraction result:", result_subtraction)

A res should produce result 50, 30

https://pynative.com/python-functions-exercise-with-solutions/

61
23CS1207- Object Oriented Programming

Skill Session:
1. Given a string of odd length greater 7, return a string made of the middle three chars of a
given String
Case 1:
str1 = "JhonDipPeta"
Expected Output:
Dip
Case 2:
str2 = "JaSonAy"
Expected Output:
Son

Program:

def get_middle_three_chars(s):
# Calculate the index of the middle character
middle_index = len(s) // 2

# Extract the middle three characters


middle_chars = s[middle_index - 1:middle_index + 2]

return middle_chars

# Test cases
str1 = "JhonDipPeta"
str2 = "JaSonAy"

# Output
print("Case 1:", get_middle_three_chars(str1)) # Output: Dip
print("Case 2:", get_middle_three_chars(str2)) # Output: Son

62
23CS1207- Object Oriented Programming

2. Arrange string characters such that lowercase letters should come first
Given an input string with the combination of the lower and upper case arrange characters in such a
way that all lowercase letters should come first.
Given:
str1 = PyNaTive
Expected Output:
yaivePNT

Program:
def arrange_lowercase_first(s):
lowercase_chars = ""
uppercase_chars = ""

# Separate lowercase and uppercase characters


for char in s:
if char.islower():
lowercase_chars += char
elif char.isupper():
uppercase_chars += char

# Concatenate lowercase and uppercase characters


arranged_string = lowercase_chars + uppercase_chars

return arranged_string

# Test case
str1 = "PyNaTive"
print(arrange_lowercase_first(str1)) # Output: yaivePNT

63
23CS1207- Object Oriented Programming

3. Reverse Words in a Given String in Python


Examples:
Input : str =" geeks quiz practice code"
Output : str = code practice quiz geeks
Input : str = "my name is laxmi"
output : str= laxmi is name my

Program:

def reverse_words(s):
# Split the string into words
words = s.split()

# Reverse the order of words


reversed_string = ' '.join(reversed(words))

return reversed_string

# Test cases
str1 = "geeks quiz practice code"
str2 = "my name is laxmi"

print("Input:", str1)
print("Output:", reverse_words(str1)) # Output: code practice quiz geeks

print("Input:", str2)
print("Output:", reverse_words(str2)) # Output: laxmi is name my

64
23CS1207- Object Oriented Programming

4. Convert numeric words to numbers


Given a string S, containing numeric words, the task is to convert the given string to the
actual number.
Example:
Input: S = “zero four zero one”
Output: 0401
Input: S = “four zero one four”
Output: 4014

Program:

def words_to_numbers(s):
# Define a dictionary to map numeric words to numbers
word_to_num = {
"zero": "0", "one": "1", "two": "2", "three": "3", "four": "4",
"five": "5", "six": "6", "seven": "7", "eight": "8", "nine": "9"
}

# Split the string into words


words = s.split()

# Convert each word to its corresponding number


numbers = [word_to_num[word] for word in words]

# Combine the numbers into a single string


result = ''.join(numbers)

return result

# Test cases
input1 = "zero four zero one"
input2 = "four zero one four"

print("Input:", input1)
print("Output:", words_to_numbers(input1)) # Output: 0401

print("Input:", input2)
print("Output:", words_to_numbers(input2)) # Output: 4014

65
23CS1207- Object Oriented Programming

66
23CS1207- Object Oriented Programming

WEEK - 6

Lab Session:

Date of the Session: / / Time of the Session: to


Prerequisite:

 Introduction to OOP principles


 Class, Objects, Methods
 Constructors, Access specifiers
 Inheritance

Pre-lab Task:
1. What is OOPs in Python?

2. Define an object?

3. Difference between Methods and constructors?

4. What are constructor and its need in python?

5. What are the Access specifiers in python?

67
23CS1207- Object Oriented Programming

In-lab Task:

1.(The Fan class) Design a class named Fan to represent a fan. The class contains:
 Three constants named SLOW, MEDIUM, and FAST with the values 1, 2, and 3 to denote the fan
speed.
 A private int data field named speed that specifies the speed of the fan.
 A private bool data field named on that specifies whether the fan is on (the default is False).
 A private float data field named radius that specifies the radius of the fan.
 A private string data field named color that specifies the color of the fan.
 The accessor and mutator methods for all four data fields.
 A constructor that creates a fan with the specified speed (default SLOW), radius (default 5), color
(default blue), and on (default False).
Write a test program that creates two Fan objects. For the first object, assign the maximum speed,
radius 10, color yellow, and turn it on. Assign medium speed, radius 5, color blue, and turn it off for the
second object. Display each object‟s speed, radius, color, and on properties.

Program:

class Fan:
# Constants for fan speeds
SLOW = 1
MEDIUM = 2
FAST = 3

def __init__(self, speed=1, radius=5, color='blue', on=False):


self.__speed = speed
self.__on = on
self.__radius = radius
self.__color = color

# Accessor and mutator methods for speed


def get_speed(self):
return self.__speed

def set_speed(self, speed):


self.__speed = speed

# Accessor and mutator methods for on


def is_on(self):
return self.__on

def set_on(self, on):


self.__on = on

# Accessor and mutator methods for radius


def get_radius(self):
return self.__radius

68
23CS1207- Object Oriented Programming

def set_radius(self, radius):


self.__radius = radius

# Accessor and mutator methods for color


def get_color(self):
return self.__color

def set_color(self, color):


self.__color = color

if __name__ == "__main__":
# Test program
fan1 = Fan(Fan.FAST, 10, 'yellow', True)
fan2 = Fan(Fan.MEDIUM, 5, 'blue', False)

# Display fan properties


print("Fan 1 properties:")
print("Speed:", fan1.get_speed())
print("Radius:", fan1.get_radius())
print("Color:", fan1.get_color())
print("On:", fan1.is_on())

print("\nFan 2 properties:")
print("Speed:", fan2.get_speed())
print("Radius:", fan2.get_radius())
print("Color:", fan2.get_color())
print("On:", fan2.is_on())

69
23CS1207- Object Oriented Programming

2.(Stopwatch) Design a class named StopWatch. The class contains:


 The private data fields startTime and endTimewith get methods.
 A constructor that initializes startTime with the current time.
 A method named start() that resets the startTimeto the current time.
 A method named stop() that sets the endTimeto the current time.
 A method named getElapsedTime() that returns the elapsed time for the stop watch in
milliseconds.
Write a test program that measures the execution time of adding numbers from 1 to 1,000,000.

Program:

import time

class StopWatch:
def __init__(self):
self.__start_time = time.time() * 1000 # storing in milliseconds
self.__end_time = None

def start(self):
self.__start_time = time.time() * 1000

def stop(self):
self.__end_time = time.time() * 1000

def get_start_time(self):
return self.__start_time

def get_end_time(self):
return self.__end_time

def get_elapsed_time(self):
if self.__end_time is None:
return None
return self.__end_time - self.__start_time

if __name__ == "__main__":
stopwatch = StopWatch()
stopwatch.start()

# Calculate sum of numbers from 1 to 1,000,000


total = 0
for i in range(1, 1000001):
total += i

stopwatch.stop()

print("Elapsed time:", stopwatch.get_elapsed_time(), "milliseconds")

70
23CS1207- Object Oriented Programming

3. The Farm Problem


In this challenge, a farmer is asking you to tell him how many legs can be counted among all his
animals. The farmer breeds three species:

chicken = 2 legs
cow= 4 legs
pig = 4 legs
The farmer has counted his animals and he gives you a sub-total for each species. You have to
implement a function that returns the total number of legs of all the animals.
Examples
animals(2, 3, 5) ➞ 36
animals(1, 2, 3) ➞ 22
animals(5, 2, 8) ➞ 50
Notes
Don't forget to return the result.
The order of animals passed is animals(chicken, cow, pig).
Remember that the farmer wants to know the total number of legs and not the total number of animals.

Program:

def animals(chicken, cow, pig):


total_legs = (chicken * 2) + (cow * 4) + (pig * 4)
return total_legs

# Test cases
print(animals(2, 3, 5)) # ➞ 36
print(animals(1, 2, 3)) # ➞ 22
print(animals(5, 2, 8)) # ➞ 50

71
23CS1207- Object Oriented Programming

Post-lab Task:

1. Determine which class a given Bus object belongs to (Check type of a object)
Given:
class Vehicle:
def init (self, name, mileage, capacity):
self.name = name
self.mileage = mileage
self.capacity = capacity
class Bus(Vehicle):
pass
School_bus = Bus("School Volvo", 12, 50)

https://pynative.com/python-object-oriented-programming-oop-exercise/

Program:

class Vehicle:
def __init__(self, name, mileage, capacity):
self.name = name
self.mileage = mileage
self.capacity = capacity

class Bus(Vehicle):
pass

School_bus = Bus("School Volvo", 12, 50)

# Checking the class of School_bus object


print(type(School_bus)) # Output: <class '__main__.Bus'>

72
23CS1207- Object Oriented Programming

2. Create a deck of cards class. Internally, the deck of cards should use another class, a card
class. Your requirements are:
The Deck class should have a deal method to deal a single card from the deck
After a card is dealt, it is removed from the deck.
There should be a shuffle method which makes sure the deck of cards has all 52 cards and
then rearranges them randomly.
The Card class should have a suit (Hearts, Diamonds, Clubs, Spades) and a value
(A,2,3,4,5,6,7,8,9,10,J,Q,K)
https://www.rithmschool.com/courses/python-fundamentals-part-2/python-object-oriented-
programming-exercises

Create a Vehicle class with max_speed and mileage instance attributes

Program:

import random

class Card:

def __init__(self, suit, value):

self.suit = suit

self.value = value

def __repr__(self):

return f"{self.value} of {self.suit}"

class Deck:

def __init__(self):

self.cards = []

self.generate_deck()

def generate_deck(self):

suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']

values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']

for suit in suits:

for value in values:

self.cards.append(Card(suit, value))

def shuffle(self):
73
23CS1207- Object Oriented Programming

random.shuffle(self.cards)

def deal(self):

if len(self.cards) == 0:

return None

return self.cards.pop()

def __repr__(self):

return f"Deck of {len(self.cards)} cards"

# Testing the classes

deck = Deck()

print(deck)

deck.shuffle()

print(deck)

card_dealt = deck.deal()

print("Card dealt:", card_dealt)


print(deck)

74
23CS1207- Object Oriented Programming

Skill Session:
1. Given Create child class Bus that will inherit all of the variables and methods of the Vehicle
class
Given:
class Vehicle:

def init (self, name, max_speed, mileage):


self.name = name
self.max_speed = max_speed
self.mileage = mileage
Create a Bus object that will inherit all of the variables and methods of the Vehicle class and
display it.

Expected Output:

Vehicle Name: School Volvo Speed: 180 Mileage: 12

Given:

Create a Bus class that inherits from the Vehicle class. Give the capacity argument of
Bus.seating_capacity() a default value of 50.

Use the following code for your parent Vehicle class. You need to use method overriding.
class Vehicle:
def init (self, name, max_speed, mileage):
self.name = name
self.max_speed = max_speed
self.mileage = mileage

defseating_capacity(self, capacity):
return f"The seating capacity of a {self.name} is {capacity} passengers"
Expected Output:
The seating capacity of a bus is 50 passengers

Program:

class Vehicle:
def __init__(self, name, max_speed, mileage):
self.name = name
self.max_speed = max_speed
self.mileage = mileage

def seating_capacity(self, capacity):


return f"The seating capacity of a {self.name} is {capacity} passengers"

# Scenario 1
class Bus(Vehicle):
pass

bus1 = Bus("School Volvo", 180, 12)


print("Vehicle Name:", bus1.name)

75
23CS1207- Object Oriented Programming

print("Speed:", bus1.max_speed)
print("Mileage:", bus1.mileage)

# Scenario 2
class Bus(Vehicle):
def seating_capacity(self, capacity=50):
return f"The seating capacity of a {self.name} is {capacity} passengers"

bus2 = Bus("bus", 180, 12)


print(bus2.seating_capacity())

76
23CS1207- Object Oriented Programming

2. Define property that should have the same value for every class instance
Define a class attribute”color” with a default value white. I.e., Every Vehicle should be
white.
Use the following code for this exercise.
class Vehicle:
def init (self, name, max_speed, mileage):
self.name = name
self.max_speed = max_speed
self.mileage = mileage

class Bus(Vehicle):
pass

class Car(Vehicle):
pass

Expected Output:
Color: White, Vehicle name: School Volvo, Speed: 180, Mileage: 12
Color: White, Vehicle name: Audi Q5, Speed: 240, Mileage: 18

Program:

class Vehicle:
color = "White" # Class attribute

def __init__(self, name, max_speed, mileage):


self.name = name
self.max_speed = max_speed
self.mileage = mileage

class Bus(Vehicle):
def __init__(self, name, max_speed, mileage):
super().__init__(name, max_speed, mileage)

class Car(Vehicle):
def __init__(self, name, max_speed, mileage):
super().__init__(name, max_speed, mileage)

# Test
bus = Bus("School Volvo", 180, 12)
print("Color:", bus.color)
print("Vehicle name:", bus.name)
print("Speed:", bus.max_speed)
print("Mileage:", bus.mileage)

car = Car("Audi Q5", 240, 18)


print("Color:", car.color)
print("Vehicle name:", car.name)
print("Speed:", car.max_speed)
print("Mileage:", car.mileage)

77
23CS1207- Object Oriented Programming

3. (The Account class) Design a class named Account that contains:


■ A private int data field named id for the account.
■ A private float data field named balance for the account.
■ A private float data field named annualInterestRate that stores the current
interest rate.
■ A constructor that creates an account with the specified id (default 0), initial
balance (default 100), and annual interest rate (default 0).
■ The accessor and mutator methods for id, balance, and annualInterestRate.
■ A method named getMonthlyInterestRate() that returns the monthly
interest rate.
■ A method named getMonthlyInterest() that returns the monthly interest.
■ A method named withdraw that withdraws a specified amount from the
account.
■ A method named deposit that deposits a specified amount to the account.
(Hint: The method getMonthlyInterest() is to return the monthly interest amount, not
the interest rate. Use this formula to calculate the monthly interest: balance *
monthlyInterestRate. monthlyInterestRate is annualInterestRate/ 12. Note that
annualInterestRate is a percent (like 4.5%). You need to divide it by 100.)

Write a test program that creates an Account object with an account id of 1122, a
balance of $20,000, and an annual interest rate of 4.5%. Use the withdraw method to
withdraw $2,500, use the deposit method to deposit $3,000, and print the id, balance,
monthly interest rate, and monthly interest.

Program:

class Account:
def __init__(self, id=0, balance=100, annual_interest_rate=0):
self.__id = id
self.__balance = balance
self.__annual_interest_rate = annual_interest_rate

def get_id(self):
return self.__id

def set_id(self, id):


self.__id = id

def get_balance(self):
return self.__balance

def set_balance(self, balance):


self.__balance = balance

def get_annual_interest_rate(self):
return self.__annual_interest_rate

def set_annual_interest_rate(self, annual_interest_rate):


self.__annual_interest_rate = annual_interest_rate

def get_monthly_interest_rate(self):
return self.__annual_interest_rate / 12 / 100
78
23CS1207- Object Oriented Programming

def get_monthly_interest(self):
return self.__balance * self.get_monthly_interest_rate()

def withdraw(self, amount):


self.__balance -= amount

def deposit(self, amount):


self.__balance += amount

# Test program
account = Account(1122, 20000, 4.5)

account.withdraw(2500)
account.deposit(3000)

print("Account ID:", account.get_id())


print("Balance:", account.get_balance())
print("Monthly Interest Rate:", account.get_monthly_interest_rate())
print("Monthly Interest:", account.get_monthly_interest())

79
23CS1207- Object Oriented Programming

80
23CS1207- Object Oriented Programming

4. (Occurrences of a specified character) Write a function that finds the number of


occurrences of a specified character in a string using the following header:

def count(s, ch):

The str class has the count method. Implement your method without using the count method.
For example, count("Welcome", 'e') returns 2.

Write a program that prompts the user to enter a string followed by a character and displays
the number of occurrences of the character in the string.

Program:

def count(s, ch):


count = 0
for char in s:
if char == ch:
count += 1
return count

# Program to prompt user input


def main():
string = input("Enter a string: ")
character = input("Enter a character: ")
occurrences = count(string, character)
print(f"Number of occurrences of '{character}' in the string: {occurrences}")

if __name__ == "__main__":
main()

81
23CS1207- Object Oriented Programming

82
23CS1207- Object Oriented Programming

WEEK - 7

Lab Session:

Date of the Session: / / Time of the Session: to


Prerequisite:
 Polymorphism
 Recursion, Nested classes

Pre-lab Task:

1. What is recursion in python?

2. Ddifferentiate between call by value and call by reference?

3. What is a nested class in Python?

4. What is polymorphism?

5. What is the scope of a nested class?

6. What is the main advantage of using nested classes in Python?

83
23CS1207- Object Oriented Programming

In-lab Task:

1. (Binary to decimal) Write a recursive function that parses a binary number as a string into a
decimal integer. The function header is as follows:

def binaryToDecimal(binaryString):

Write a test program that prompts the user to enter a binary string and displays it‟s decimal
equivalent.

Program:

def binaryToDecimal(binaryString):
# Base case: if the binary string is empty, return 0
if len(binaryString) == 0:
return 0
# Recursive case: convert the binary string except the last digit to decimal and multiply by 2,
# then add the last digit (0 or 1) to the result
return binaryToDecimal(binaryString[:-1]) * 2 + int(binaryString[-1])

def main():
binary_string = input("Enter a binary string: ")
decimal_value = binaryToDecimal(binary_string)
print("Decimal equivalent:", decimal_value)

if __name__ == "__main__":
main()

84
23CS1207- Object Oriented Programming

2. (String permutation) Write a recursive function to print all the permutations of a string. For
example, for the string abc, the printout is:
abc
acb
bac
bca
cab
cba
(Hint: Define the following two functions. The second function is a helper function.

def display Permutation (s):


def display Permutation Helper(s1, s2):

The first function simply invokes display Permutation(" ", s). The second function uses a loop to
move a character from s2 to s1 and recursively invokes it with a new s1 and s2. The base case is
that s2 is empty and prints s1 to the console.) Write a test program that prompts the user to enter a
string and displays all its permutations.

Program:

def displayPermutation(s):

displayPermutationHelper("", s)

def displayPermutationHelper(s1, s2):

if len(s2) == 0:

print(s1)

else:

for i in range(len(s2)):

displayPermutationHelper(s1 + s2[i], s2[:i] + s2[i+1:])

def main():

string = input("Enter a string: ")

print("Permutations:")

displayPermutation(string)

if __name__ == "__main__":

main()

85
23CS1207- Object Oriented Programming

3. Show the print out of the following program:


class A:
def new (self):
self. init (self)
print("A's new () invoked")
def init (self):
print("A's init () invoked")
class B(A):
def new (self):
self. init (self)
print("B's new () invoked")
def init (self):
print("B's init () invoked")
def main():
b = B()
a = A()
main() # Call the main function

Program:

A's init() invoked


B's init() invoked
B's new() invoked
A's init() invoked

86
23CS1207- Object Oriented Programming

Post-lab Task:

1. Show the print out of the following program:


class A:
def init (self):
print("A's init () invoked")
class B(A):
def init (self):
print("B's init () invoked")
def main():
b = B()
a = A()
main() # Call the main function

Program:

B's init()
invoked
A's init()
invoked

87
23CS1207- Object Oriented Programming

2. Suppose that Fruit, Apple, Orange, Golden Delicious, and McIntosh are
defined in the inheritance hierarchy as follows:

Assume that the following statements are given:


goldenDelicious = GoldenDelicious()
orange = Orange()
Answer the following questions:
(a) Is goldenDelicious an instance of Fruit?
(b) Is goldenDelicious an instance of Orange?
(c) Is goldenDelicious an instance of Apple?
(d) Is goldenDelicious an instance of GoldenDelicious?
(e) Is goldenDelicious an instance of McIntosh?
(f) Is orange an instance of Orange?
(g) Is orange an instance of Fruit?
(h) Is orange an instance of Apple?
(i) Suppose the method make Apple Cider is defined in the Apple class. Can golden Delicious
invoke this method? Can orange invoke this method?
( j) Suppose the method make Orange Juice is defined in the Orange class. Can orange invoke
this method? Can golden Delicious invoke this method?

Program:

a) Is goldenDelicious an instance of Fruit?

 Yes, because GoldenDelicious inherits from Fruit, so instances of GoldenDelicious are also instances of Fruit.

(b) Is goldenDelicious an instance of Orange?

 No, because goldenDelicious is an instance of GoldenDelicious, not Orange.

(c) Is goldenDelicious an instance of Apple?

 No, because GoldenDelicious is a subclass of Apple, not an instance of Apple directly.

(d) Is goldenDelicious an instance of GoldenDelicious?

 Yes, goldenDelicious is an instance of GoldenDelicious because it's explicitly defined as such.

(e) Is goldenDelicious an instance of McIntosh?

88
23CS1207- Object Oriented Programming

 No, unless GoldenDelicious inherits from McIntosh, which is not specified in the given hierarchy.

(f) Is orange an instance of Orange?

 Yes, because orange is explicitly defined as an instance of Orange.

(g) Is orange an instance of Fruit?

 Yes, because Orange inherits from Fruit, so instances of Orange are also instances of Fruit.

(h) Is orange an instance of Apple?

 No, because Orange is a different class from Apple.

(i) Can goldenDelicious invoke the method makeAppleCider?

 No, because makeAppleCider is defined in the Apple class, and GoldenDelicious is not a subclass of Apple.

Can orange invoke the method makeAppleCider?

 No, for the same reason as above.

(j) Can orange invoke the method makeOrangeJuice?

 Yes, because makeOrangeJuice is defined in the Orange class, and orange is an instance of Orange.

Can goldenDelicious invoke the method makeOrangeJuice?

 No, because makeOrangeJuice is not defined in the GoldenDelicious class or any of its superclasses.

89
23CS1207- Object Oriented Programming

90
23CS1207- Object Oriented Programming

Skill Session:
1. Write a shutting down program:
First, def a function, shut_down, that takes one argument s. Then, if the shut_down function
receives an s equal to "yes", it should return "Shutting down" Alternatively, elif s is equal to
"no", then the function should return "Shutdown aborted". Finally, if shut_down gets
anything other than those inputs, the function should return "Sorry".

Program:

def shut_down(s):
if s == "yes":
return "Shutting down"
elif s == "no":
return "Shutdown aborted"
else:
return "Sorry"

# Test the function


print(shut_down("yes")) # Output: Shutting down
print(shut_down("no")) # Output: Shutdown aborted
print(shut_down("maybe")) # Output: Sorry

91
23CS1207- Object Oriented Programming

2. Define two classes Parrot and Penguin. Each of them have a common fly() method.
However, their functions are different. To use polymorphism, create a common interface
i.e flying_test() function that takes any object and calls the object's fly() method. pass
the blu and Peggy objects in the flying_test() function.

Program:

class Parrot:

def fly(self):

return "Parrot can fly"

class Penguin:

def fly(self):

return "Penguin can't fly"

def flying_test(bird):

return bird.fly()

# Creating instances of Parrot and Penguin

blu = Parrot()

peggy = Penguin()

# Calling flying_test function with different objects

print(flying_test(blu)) # Output: Parrot can fly

print(flying_test(peggy)) # Output: Penguin can't fly

92
23CS1207- Object Oriented Programming

3. First, def a function called distance_from_zero, with one argument (choose any argument
name you like). If the type of the argument is either int or float, the function should return the
absolute value of the function input. Otherwise, the function should return "Nope". Check if
it works calling the function with -5.6 and "what?".

Program:

def distance_from_zero(num):

if isinstance(num, (int, float)):

return abs(num)

else:

return "Nope"

# Test the function

print(distance_from_zero(-5.6)) # Output: 5.6

print(distance_from_zero("what?")) # Output: Nope

93
23CS1207- Object Oriented Programming

4. Sub classing. Now, make a subclass of Mylist from Exercise 2 called MylistSub, which
extends Mylist to print a message to stdout before each overloaded operation is called and
counts the number of calls. MylistSub should inherit basic method behav•ior from Mylist.
For instance, adding a sequence to a MylistSub should print a mes•sage, increment the
counter for + calls, and perform the superclass‟s method. Also introduce a new method that
displays the operation counters to stdout and experi•ment with your class interactively. Do
your counters count calls per instance, or per class (for all instances of the class)? How
would you program both of these? (Hint: it depends on which object the count members are
assigned to: class members are shared by instances, self members are per-instance data.)

Program:

class MyListSub(MyList):

add_counter = 0

mul_counter = 0

def __init__(self, *args):

super().__init__(*args)

def __add__(self, other):

print("Overloaded operation + called")

MyListSub.add_counter += 1

return super().__add__(other)

def __mul__(self, other):

print("Overloaded operation * called")

MyListSub.mul_counter += 1

return super().__mul__(other)

def display_counters(self):

print("Addition counter:", MyListSub.add_counter)

print("Multiplication counter:", MyListSub.mul_counter)

# Test the subclass

94
23CS1207- Object Oriented Programming

my_list_sub = MyListSub([1, 2, 3])

other_list = [4, 5, 6]

result_add = my_list_sub + other_list # Calls __add__ method

print("Result of addition:", result_add)

result_mul = my_list_sub * 3 # Calls __mul__ method

print("Result of multiplication:", result_mul)

my_list_sub.display_counters()

95
23CS1207- Object Oriented Programming

96
23CS1207- Object Oriented Programming

WEEK - 8

Lab Session:

Date of the Session: / / Time of the Session: to


Prerequisite:

 FILES.

Pre-lab Task:

1. What are the types of files in file handling in Python?

2. How do you create write and append to a file in Python?

3. What are the file operations in Python and explain?

4. What are the file opening modes for text files?

5. Write one basic difference between Text file and Binary file in Python?

97
23CS1207- Object Oriented Programming

In-lab Task:

1. Write a program in python to display number of lines in a text file (“klu.txt”)

Program:

# Open the file in read mode


with open("klu.txt", "r") as file:
# Read all lines into a list
lines = file.readlines()

# Count the number of lines


num_lines = len(lines)

# Display the number of lines


print("Number of lines in the file:", num_lines)

98
23CS1207- Object Oriented Programming

2. Roman to Integer
Roman numerals are represented by seven different
symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

Example 1:
Input: s = "III"
Output: 3

Example 2:
Input: s = "IV"
Output: 4

Program:

def roman_to_int(s):
# Dictionary to store the values corresponding to each Roman numeral
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}

# Initialize result
result = 0

# Iterate through the string


for i in range(len(s)):
# If the current Roman numeral is smaller than the next one, subtract its value
if i < len(s) - 1 and roman_dict[s[i]] < roman_dict[s[i + 1]]:
result -= roman_dict[s[i]]
else:
result += roman_dict[s[i]]

return result

# Test the function


print(roman_to_int("III"))
print(roman_to_int("IV"))

99
23CS1207- Object Oriented Programming

3. Write program in python to count number of vowels in a file (“klu.txt”)

Program:
# Function to count vowels in a string
def count_vowels(string):
vowels = 'aeiouAEIOU'
count = 0
for char in string:
if char in vowels:
count += 1
return count

# Open the file in read mode


with open("klu.txt", "r") as file:
# Read the content of the file
content = file.read()

# Count the number of vowels in the content


num_vowels = count_vowels(content)

# Display the result


print("Number of vowels in the file:", num_vowels)

100
23CS1207- Object Oriented Programming

Post-lab Task:

1. (Create large dataset) Create a data file with 1000 lines. Each line in the file consists of a
faculty first name, last name, rank, and salary. Faculty‟s first name and last name for the i th line are
FirstName and LastName. The rank is randomly generated as assistant, associate, and full. The
salary is randomly generated as a number with two digits after the decimal point. The salary for
assistant professor should be in the range from 50,000 to 80,000, for associate professor from
60,000 to 110,000, and for full professor from 75,000 to 130,000. Save the file in Salary.txt. Here
are some sample data.
FirstName1 LastName1 assistant 60055.95
FirstName2 LastName2 associate 81112.45
...
FirstName1000 LastName1000 full 92255.21

Program:

import random

# Function to generate random salary based on rank


def generate_salary(rank):
if rank == "assistant":
return round(random.uniform(50000, 80000), 2)
elif rank == "associate":
return round(random.uniform(60000, 110000), 2)
elif rank == "full":
return round(random.uniform(75000, 130000), 2)

# Open the file for writing


with open("Salary.txt", "w") as file:
# Generate 1000 lines of data
for i in range(1, 1001):
# Generate random rank
rank = random.choice(["assistant", "associate", "full"])

# Generate random salary based on rank


salary = generate_salary(rank)

# Write data to file


file.write(f"FirstName{i} LastName{i} {rank} {salary}\n")

101
23CS1207- Object Oriented Programming

2. Write a program to prompt for a file name, and then read through the file line-by-line. Note: the
file name is Erle.txt and its content is, Erle is the enabling technology for the next generation of
aerial and terrestrial robots that will be used in cities solving tasks such as surveillance,
environmental monitoring or even providing aid at catastrophes. Ensure you create the file.

Program:

# Prompt the user for a file name


file_name = input("Enter the file name: ")

try:
# Open the file for reading
with open(file_name, "r") as file:
# Read the file line-by-line
for line in file:
# Print each line
print(line.strip())
except FileNotFoundError:
print("File not found.")

102
23CS1207- Object Oriented Programming

Skill Session:

1. Write all file content into new file by skiping line 5 from following file test.txt file:
line1
line2
line3
line4
line5
line6
line7

newFile.txt should be
line1
line2
line3
line4
line6
line7
Assume you have a file called students.txt which simply contains a bunch of student names,
one name per line. Your goal is to write two functions: add_student - accepts a parameter of
first_name and writes to a file called students.txt. find_student - accepts a parameter of
first_name and returns the first student found

Program:

# Open the original file for reading


with open("test.txt", "r") as original_file:
# Read all lines into a list
lines = original_file.readlines()

# Skip line 5
lines.pop(4)

# Open a new file for writing


with open("newFile.txt", "w") as new_file:
# Write the modified content to the new file
new_file.writelines(lines)

or

def add_student(first_name):
# Open the file in append mode and write the new student name
with open("students.txt", "a") as file:
file.write(first_name + "\n")

def find_student(first_name):
# Open the file for reading
with open("students.txt", "r") as file:
# Iterate through each line
for line in file:
103
23CS1207- Object Oriented Programming

# Strip newline characters and compare with the given first name
if line.strip() == first_name:
return first_name # Return the first occurrence of the student name

return None # Return None if the student name is not found

# Test the functions


add_student("John Doe")
add_student("Alice Smith")

print(find_student("John Doe")) # Output: John Doe


print(find_student("Alice Smith")) # Output: Alice Smith
print(find_student("Bob Johnson")) # Output: None (if Bob Johnson is not in the file)

104
23CS1207- Object Oriented Programming

2. Write the following additional functions:


update_student - accepts a parameter of first_name and new_name and updates first student
found remove_student - accepts a parameter of first_name and removes the student from the
text file Add a unique id for each student so that you can find a student by their id instead of
first name (which breaks if you have the same first name for multiple students)

Program:

def add_student(first_name, unique_id):


# Open the file in append mode and write the new student information
with open("students.txt", "a") as file:
file.write(f"{unique_id},{first_name}\n")

def update_student(first_name, new_name):


# Read the file content into a list
with open("students.txt", "r") as file:
lines = file.readlines()

# Iterate through each line


for i, line in enumerate(lines):
# Split the line into ID and first name
unique_id, name = line.strip().split(",")
# If the first name matches, update the name
if name == first_name:
lines[i] = f"{unique_id},{new_name}\n"
break

# Write the modified content back to the file


with open("students.txt", "w") as file:
file.writelines(lines)

def remove_student(first_name):
# Read the file content into a list
with open("students.txt", "r") as file:
lines = file.readlines()

# Iterate through each line


for i, line in enumerate(lines):
# Split the line into ID and first name
unique_id, name = line.strip().split(",")
# If the first name matches, remove the line
if name == first_name:
del lines[i]
break

# Write the modified content back to the file


with open("students.txt", "w") as file:
file.writelines(lines)

def find_student_by_id(unique_id):
# Open the file for reading
with open("students.txt", "r") as file:

105
23CS1207- Object Oriented Programming

# Iterate through each line


for line in file:
# Split the line into ID and first name
line_id, name = line.strip().split(",")
# If the ID matches, return the first name
if line_id == unique_id:
return name

return None # Return None if the ID is not found

# Test the functions


add_student("John Doe", "1")
add_student("Alice Smith", "2")
add_student("John Smith", "3")

print(find_student_by_id("2")) # Output: Alice Smith

update_student("John Doe", "Johnny Doe")


print(find_student_by_id("1")) # Output: Johnny Doe

remove_student("John Smith")
print(find_student_by_id("3")) # Output: None (John Smith should be removed)

106
23CS1207- Object Oriented Programming

3. For the next part of this exercise, you will be working with CSVs, so first create a file called
users.csv and then work on the following two functions:
one that prints out all of the first and last names in the users.csv file
one that prompts us to enter a first and last name and adds it to the users.csv file.

Program:

import csv

# Sample data for the CSV file


data = [
{"First Name": "John", "Last Name": "Doe"},
{"First Name": "Alice", "Last Name": "Smith"},
{"First Name": "Bob", "Last Name": "Johnson"}
]

# Write the data to the CSV file


with open("users.csv", "w", newline='') as file:
writer = csv.DictWriter(file, fieldnames=["First Name", "Last Name"])
writer.writeheader()
writer.writerows(data)

import csv

def print_names_from_csv(file_name):
# Open the CSV file for reading
with open(file_name, "r", newline='') as file:
reader = csv.DictReader(file)
# Print the first and last names from each row
for row in reader:
print(f"{row['First Name']} {row['Last Name']}")

def add_user_to_csv(file_name, first_name, last_name):


# Append the new user to the CSV file
with open(file_name, "a", newline='') as file:
writer = csv.writer(file)
writer.writerow([first_name, last_name])

# Test the functions


print("All first and last names in users.csv:")
print_names_from_csv("users.csv")

first_name = input("Enter the first name: ")


last_name = input("Enter the last name: ")
add_user_to_csv("users.csv", first_name, last_name)

print("User added successfully.")

107
23CS1207- Object Oriented Programming

4. Define a Point3D class that inherits from object Inside the Point3D class, define an init ()
function that accepts self, x, y, and z, and assigns these numbers to the member variables
self.x,self.y,self.z. Define a repr () method that returns "(%d, %d, %d)" % (self.x, self.y,
self.z). This tells Python to represent this object in the following format: (x, y, z). Outside the
class definition, create a variable named my_point containing a new instance of Point3D with
x=1, y=2, and z=3. Finally, print my_point.

Program:

class Point3D(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z

def __repr__(self):
return "(%d, %d, %d)" % (self.x, self.y, self.z)

# Create an instance of Point3D


my_point = Point3D(1, 2, 3)

# Print my_point
print(my_point)

108
23CS1207- Object Oriented Programming

109
23CS1207- Object Oriented Programming

WEEK - 9

Lab Session:

Date of the Session: / / Time of the Session: to


Prerequisite:

 Packages
 Importing packages
 Extending interfaces

Pre-lab Task:

1. What is Package?

2. What are the import packages in Python?

3. How to import user defined package in Python?

4. How to create packages in Python?

5. Difference between packages and module?

110
23CS1207- Object Oriented Programming

In-lab Task:
1. Back to Home?
Mubashir has started his journey from home. Given a string of directions (N=North, W=West,
S=South, E=East), he will walk for one minute in each direction. Determine whether a set of
directions will lead him back to the starting position or not.
Examples
back_to_home("EEWE") ➞ False
back_to_home("NENESSWW") ➞ True
back_to_home("NEESSW") ➞ False

Program:

111
23CS1207- Object Oriented Programming

2. Nested imports. Write a second module, myclient.py, which imports mymod and tests its functions;
run myclient from the system command line. If myclient uses from to fetch from mymod, will
mymod‟s functions be accessible from the top level of myclient? What if it imports with import
instead? Try coding both variations in myclient and test interactively, by importing myclient and
inspecting its dict .

Program:

112
23CS1207- Object Oriented Programming

3. Package imports. Finally, import your file from a package. Create a sub-directory called mypkg
nested in a directory on your module import search path, move the mymod.py module file you
created in exercises 1 or 3 into the new directory, and try to import it with a package import of the
form: import mypkg.mymod.
You‟ll need to add an init .py file in the directory your module was moved to in order to make
this go, but it should work on all major Python platforms (that‟s part of the reason Python uses “.”
as a path separator). The package directory you create can be simply a subdirectory of the one
you‟re working in; if it is, it will be found via the home directory component of the search path,
and you won‟t have to configure your path. Add some code to your init .py, and see if it runs
on each import.

Program:

113
23CS1207- Object Oriented Programming

Post-lab Task:

1. Write a program to import the package named matplotlib.

Program:

114
23CS1207- Object Oriented Programming

2. Create a sub-package road with modules cars and bikes in the package transport. Both modules

must contain a function that prints a string of that module name. Also create another python file to

run the two functions

Program:

115
23CS1207- Object Oriented Programming

Skill Session:
1. Basics, import. Write a program that counts lines and characters in a file (similar in spirit to
“wc” on Unix). With your favorite text editor, code a Python module called mymod.py,
which exports three top-level names:
a) A countLines(name) function that reads an input file and counts the number of lines in it
(hint: file.readlines() does most of the work for you, and len does the rest)
b) A countChars(name) function that reads an input file and counts the number of
characters in it (hint: file.read() returns a single string)
c) A test(name) function that calls both counting functions with a given input file•name.
Such a filename generally might be passed-in, hard-coded, input with raw_input, or pulled
from a command-line via the sys.argv list; for now, assume it‟s a passed-in function
argument.
All three mymod functions should expect a filename string to be passed in. If you type
more than two or three lines per function, you‟re working much too hard—use the hints
listed above!
Now, test your module interactively, using import and name qualification to fetch your
exports. Does your PYTHONPATH need to include the directory where you created
mymod.py? Try running your module on itself: e.g., test("mymod.py"). Note that test opens
the file twice; if you‟re feeling ambitious, you may be able to improve this by passing an
open file object into the two count functions (hint: file.seek(0) is a file rewind).

Program:

116
23CS1207- Object Oriented Programming

117
23CS1207- Object Oriented Programming

WEEK - 10

Lab Session:

Date of the Session: / / Time of the Session: to


Prerequisite:

 Exceptions Handling
 try, catch, finally

Pre-lab Task:

1. What is an Exception in Python?

2. What are the Exception Handling Keywords in Python?

3. Explain Python Exception Hierarchy?

4. Can we have an empty catch block?

5. What happens when an exception is thrown by the main method?

118
23CS1207- Object Oriented Programming

In-lab Task:

1. Words Score Input Format

The input is read by the provided locked code template. In the first line, there is a single integer n

denoting the number of words. In the second line, there are n space-separated lowercase words.

Constraints

Each word has at most letters and all letters are English lowercase letters

Output Format

The output is produced by the provided and locked code template. It calls

function score_words with the list of words read from the input as the argument and prints the

returned score to the output.

Sample Input 0

Sample Output 0 :4

LINK: https://www.hackerrank.com/challenges/words-score/problem

Program:

119
23CS1207- Object Oriented Programming

2. (The Triangle Error class)

Define an exception class named TriangleErrorthat extends RuntimeError. The TriangleErrorclass

contains the privatedata fieldsside1, side2, and side3 with accessor methods for the threesides of a

triangle. Modify the Triangle class to throw aTriangleErrorexception if the three given sides

cannot form a triangle.

Program:

120
23CS1207- Object Oriented Programming

3. (try/except. Write a function called oops that explicitly raises an IndexError exception when called.

Then write another function that calls oops inside a try/except state•ment to catch the error. What

happens if you change oops to raise KeyError instead of IndexError? Where do the names

KeyError and IndexError come from? (Hint: recall that all unqualified names come from one of

four scopes, by the LEGB rule.)

LINK: https://learning-python.com/class/Workbook/x-exercises.htm

Program:

121
23CS1207- Object Oriented Programming

Post-lab Task:

1. Complete the exercise problems given in the link provided

https://holypython.com/beginner-python-exercises/exercise-15-error handling/

Program:

122
23CS1207- Object Oriented Programming

2. Exceptions:

Sample Input
3
10
2$
31

Sample Output
Error Code: integer division or modulo by zero
Error Code: invalid literal for int() with base 10: '$'
3

LINK: https://www.hackerrank.com/challenges/exceptions/problem

Program:

123
23CS1207- Object Oriented Programming

Skill Session:

1. Exception objects and lists. Change the oops function you just wrote to raise an exception you
define yourself, called MyError, and pass an extra data item along with the exception. You may identify
your exception with either a string or a class. Then, extend the try statement in the catcher function to
catch this exception and its data in addition to IndexError, and print the extra data item. Finally, if you
used a string for your exception, go back and change it be a class instance; what now comes back as the
extra data to the handler?
https://learning-python.com/class/Workbook/x-exercises.htm

Program:

124
23CS1207- Object Oriented Programming

2. E Error handling. Write a function called safe(func,*args) that runs any function using the
func(*args) call syntax (formerly known as the apply built-in function), catches any exception raised
while the function runs, and prints the exception using the exc_info() call in the sys module. Then, use
your safe function to run the oops function you wrote in Exercises 1 and/or 2. Put safe in a module file
called tools.py, and pass it the oops function interactively. What sort of error messages do you get?
Finally, expand safe to also print a Python stack trace when an error occurs by calling the built-in
print_exc() function in the standard tra•ceback module (use exc_info()[2], and see the Python library
reference manual for details).

https://learning-python.com/class/Workbook/x-exercises.htm

Program:

125
23CS1207- Object Oriented Programming

3. Error handling: the Pdb debugger. Run the “oops” function from (1) or (2) under the pdb

debugger interactively. Import pdb and “oops”, run a call string, and type “c” (continue) commands

till the error occurs. Where are you when the debugger stops? Type a „where‟ command to find out.

Now, type „quit‟ and rerun the program: set a break point on the “oops” function, and single-step up

to the error. Experiment with “up” and “down” commands—they climb and descend the Python call

stack. See the library manual for more details on pdb debugging, or use the point-and-click debugger

interface in the IDLE GUI

https://learning-python.com/class/Workbook/x-exercises.htm

Program:

126
23CS1207- Object Oriented Programming

WEEK - 11

Lab Session:

Date of the Session: / / Time of the Session: to


Prerequisite:
 Multi-threading
 Multitasking

Pre-lab Task:

1. What is thread and how to implement?

2. What is multithreading and multitasking?

3. How many threads can run at once in Python?

4. What are the benefits of using multithreading in


Python?

5. Is it possible to create multiple processes from within a single thread? If yes, then how?

127
23CS1207- Object Oriented Programming

In-lab Task:

1. Create a set of threads to count how many lines there are in a set of (presumably large) text
files. You may choose the number of threads to use. Compare the performance against a single-
threaded version of this code.
REF:https://flylib.com/books/en/2.108.1.233/1/

Program:

128
23CS1207- Object Oriented Programming

2. C Write a program where in a thread waits for a particular event indefinitely. once the event is
set by the main thread, the thread stops waiting and resumes execution.

Program:

129
23CS1207- Object Oriented Programming

3. C Write a program which creates 2 threads which does the following without conflict:
Acquire the lock, increment the counter value and release the lock.

Program:

130
23CS1207- Object Oriented Programming

Post-lab Task:

1. Write a program to create 5 threads which in turn each will print 'hello world' on the screen

Program:

131
23CS1207- Object Oriented Programming

2. Write a program to create a thread which will print 'hello world' on the screen

Program:

132
23CS1207- Object Oriented Programming

Skill Session:

1. Write a program to create a thread which adds 2 numbers and prints the result

Program:

133
23CS1207- Object Oriented Programming

2. Write a program which creates a thread, officially names it and tries to print the official name of the
thread

Program:

134
23CS1207- Object Oriented Programming

3. Write a program to create a thread which is not dependent on the main thread (create a daemon
thread)

Program:

135
23CS1207- Object Oriented Programming

4. Write a Python program to create multiple threads and print their names.

Program:

136
23CS1207- Object Oriented Programming

WEEK - 12

Lab Session:

Date of the Session: / / Time of the Session: to


Prerequisite:
 Multitasking
 Multiprocessing

Pre-lab Task:

1. What is multiprocessing?

2. What is the difference between multi threading and multi processing in Python?

3. What are the differences between multi processing and multitasking in Python?

4. Why multiprocessing in python?

5. Advantages of Multi processing in Python?

137
23CS1207- Object Oriented Programming

In-lab Task:
1. Write a Python program to download multiple files concurrently using threads.

Program:

138
23CS1207- Object Oriented Programming

2. Write a Python program that creates two threads to find and print even and odd numbers from 30 to
50.

Program:

139
23CS1207- Object Oriented Programming

3. Write a Python program to calculate the factorial of a number using multiple threads

Program:

140
23CS1207- Object Oriented Programming

Post-lab Task:

1. Write a Python program to implement a multi-threaded merge sort algorithm.


Program:

141
23CS1207- Object Oriented Programming

2. Write a Python program to implement a multi-threaded Quick sort algorithm.


Program:

142
23CS1207- Object Oriented Programming

Skill Session:

1. Write a Python program that performs concurrent HTTP requests using threads.

Program:

143
23CS1207- Object Oriented Programming

2. Write a Python program to print the “Welcome to KLU” using Multi processing.

Program:

144
23CS1207- Object Oriented Programming

3. Write a Python program running a Function in a Process with Arguments.

Program:

145
23CS1207- Object Oriented Programming

4. Write a Python program getting id and checking if the process is alive

Program:

146
23CS1207- Object Oriented Programming

147
23CS1207- Object Oriented Programming

148
23CS1207- Object Oriented Programming

149
23CS1207- Object Oriented Programming

150

You might also like