OOP Lab Workbook Guide
OOP Lab Workbook Guide
LABORATORY WORKBOOK
Register Number:
Year:
FIRST
Semester:
EVEN
Section:
1
23CS1207- Object Oriented Programming
INDEX
Remarks
Exp.No Date Title of the
Programs &
Signature
1
10
11
12
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
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
4
23CS1207- Object Oriented Programming
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
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
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
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
Skill Session(50M)
Sl Total Faculty Signature
No Date Experiment LOGIC EXECUTION RESULT ANALYSIS (50M)
Name (20M) (10M) (10M) (10M)
10
11
12
WEEK - 1
Lab Session:
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.
3. What are the basic data types in Python, and how are they used in programming?
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:
Expected Output:
So use one of the formatting argument of print() to turn the output into My**Name**Is**James
Program:
14
23CS1207- Object Oriented Programming
Expected Output:
Display 458.541315 as 458.54
Program:
15
23CS1207- Object Oriented Programming
Skill Session:
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
https://holypython.com/beginner-python-exercises/exercise-2-python-variables/
Program:
17
23CS1207- Object Oriented Programming
https://holypython.com/beginner-python-exercises/exercise-3-python-data-types/
Program:
18
23CS1207- Object Oriented Programming
Program:
19
23CS1207- Object Oriented Programming
WEEK - 2
Lab Session:
Conditional Statements
Operators
Pre-lab Task:
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:
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 main():
month = int(input("Enter the month (1-12): "))
year = int(input("Enter the 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"
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
Program:
24
23CS1207- Object Oriented Programming
Post-lab Task:
Program:
# 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
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”))
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
# 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:
Prerequisite:
Loops
List
Pre-lab Task:
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:
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
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:
Program:
list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]
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
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.
Program:
import math
print("Number\tSquare Root")
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:
Lists comprehension
Tuple
Set, Dictionary
Pre-lab Task:
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
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
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
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]))
L.append(int(cmd[1]))
47
23CS1207- Object Oriented Programming
L.pop();
print(L)
L.remove(int(cmd[1]))
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)
]
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
Expected output:
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
}
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
54
23CS1207- Object Oriented Programming
55
23CS1207- Object Oriented Programming
WEEK - 5
Lab Session:
Functions
Strings
Pre-lab Task:
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:
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))
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 :
Program:
def print_pascals_triangle(n):
for i in range(n):
# Print leading spaces for formatting
print(" " * (n - i - 1), end="")
# 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:
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:
# Example usage:
result_addition, result_subtraction = calculation(5, 3)
print("Addition result:", result_addition)
print("Subtraction result:", result_subtraction)
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
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 = ""
return arranged_string
# Test case
str1 = "PyNaTive"
print(arrange_lowercase_first(str1)) # Output: yaivePNT
63
23CS1207- Object Oriented Programming
Program:
def reverse_words(s):
# Split the string into words
words = s.split()
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
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"
}
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:
Pre-lab Task:
1. What is OOPs in Python?
2. Define an object?
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
68
23CS1207- Object Oriented Programming
if __name__ == "__main__":
# Test program
fan1 = Fan(Fan.FAST, 10, 'yellow', True)
fan2 = Fan(Fan.MEDIUM, 5, 'blue', False)
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
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()
stopwatch.stop()
70
23CS1207- Object Oriented Programming
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:
# 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
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
Program:
import random
class Card:
self.suit = suit
self.value = value
def __repr__(self):
class Deck:
def __init__(self):
self.cards = []
self.generate_deck()
def generate_deck(self):
values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
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):
deck = Deck()
print(deck)
deck.shuffle()
print(deck)
card_dealt = deck.deal()
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:
Expected Output:
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
# Scenario 1
class Bus(Vehicle):
pass
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"
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
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)
77
23CS1207- Object Oriented Programming
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 get_balance(self):
return self.__balance
def get_annual_interest_rate(self):
return self.__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()
# Test program
account = Account(1122, 20000, 4.5)
account.withdraw(2500)
account.deposit(3000)
79
23CS1207- Object Oriented Programming
80
23CS1207- Object Oriented Programming
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:
if __name__ == "__main__":
main()
81
23CS1207- Object Oriented Programming
82
23CS1207- Object Oriented Programming
WEEK - 7
Lab Session:
Pre-lab Task:
4. What is polymorphism?
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.
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)
if len(s2) == 0:
print(s1)
else:
for i in range(len(s2)):
def main():
print("Permutations:")
displayPermutation(string)
if __name__ == "__main__":
main()
85
23CS1207- Object Oriented Programming
Program:
86
23CS1207- Object Oriented Programming
Post-lab Task:
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:
Program:
Yes, because GoldenDelicious inherits from Fruit, so instances of GoldenDelicious are also instances of Fruit.
88
23CS1207- Object Oriented Programming
No, unless GoldenDelicious inherits from McIntosh, which is not specified in the given hierarchy.
Yes, because Orange inherits from Fruit, so instances of Orange are also instances of Fruit.
No, because makeAppleCider is defined in the Apple class, and GoldenDelicious is not a subclass of Apple.
Yes, because makeOrangeJuice is defined in the Orange class, and orange is an instance of Orange.
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"
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):
class Penguin:
def fly(self):
def flying_test(bird):
return bird.fly()
blu = Parrot()
peggy = Penguin()
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):
return abs(num)
else:
return "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
super().__init__(*args)
MyListSub.add_counter += 1
return super().__add__(other)
MyListSub.mul_counter += 1
return super().__mul__(other)
def display_counters(self):
94
23CS1207- Object Oriented Programming
other_list = [4, 5, 6]
my_list_sub.display_counters()
95
23CS1207- Object Oriented Programming
96
23CS1207- Object Oriented Programming
WEEK - 8
Lab Session:
FILES.
Pre-lab Task:
5. Write one basic difference between Text file and Binary file in Python?
97
23CS1207- Object Oriented Programming
In-lab Task:
Program:
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
return result
99
23CS1207- Object Oriented Programming
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
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
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:
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:
# Skip line 5
lines.pop(4)
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
104
23CS1207- Object Oriented Programming
Program:
def remove_student(first_name):
# Read the file content into a list
with open("students.txt", "r") as file:
lines = file.readlines()
def find_student_by_id(unique_id):
# Open the file for reading
with open("students.txt", "r") as file:
105
23CS1207- Object Oriented Programming
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
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']}")
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)
# Print my_point
print(my_point)
108
23CS1207- Object Oriented Programming
109
23CS1207- Object Oriented Programming
WEEK - 9
Lab Session:
Packages
Importing packages
Extending interfaces
Pre-lab Task:
1. What is Package?
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:
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
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:
Exceptions Handling
try, catch, finally
Pre-lab Task:
118
23CS1207- Object Oriented Programming
In-lab Task:
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
Sample Input 0
Sample Output 0 :4
LINK: https://www.hackerrank.com/challenges/words-score/problem
Program:
119
23CS1207- Object Oriented Programming
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
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
LINK: https://learning-python.com/class/Workbook/x-exercises.htm
Program:
121
23CS1207- Object Oriented Programming
Post-lab Task:
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
https://learning-python.com/class/Workbook/x-exercises.htm
Program:
126
23CS1207- Object Oriented Programming
WEEK - 11
Lab Session:
Pre-lab Task:
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:
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?
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:
141
23CS1207- Object Oriented Programming
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
Program:
145
23CS1207- Object Oriented Programming
Program:
146
23CS1207- Object Oriented Programming
147
23CS1207- Object Oriented Programming
148
23CS1207- Object Oriented Programming
149
23CS1207- Object Oriented Programming
150