0% found this document useful (0 votes)
49 views26 pages

University of Engineering and Technology Taxila: Engr. Asma Shafi Muhammad Jarrar Mehdi (22-TE-04) OOP Lab Manuals

The document provides source code and documentation for several Python programs related to object-oriented programming concepts and data structures. It includes programs to: 1. Calculate the distance between two points and sum of command line arguments in 1-2 sentences. 2. Check if a number is even, calculate factorials, and print prime numbers below 100 using control flow structures like if/else in 1 sentence. 3. Count character frequencies in a string and split/join a birthday string using dictionary in 1 sentence. 4. Find mean, median, mode of a list and find duplicate elements in a list using a function in 1 sentence. 5. Demonstrate addition and multiplication of 2D matrices using

Uploaded by

Jarrar Malik
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)
49 views26 pages

University of Engineering and Technology Taxila: Engr. Asma Shafi Muhammad Jarrar Mehdi (22-TE-04) OOP Lab Manuals

The document provides source code and documentation for several Python programs related to object-oriented programming concepts and data structures. It includes programs to: 1. Calculate the distance between two points and sum of command line arguments in 1-2 sentences. 2. Check if a number is even, calculate factorials, and print prime numbers below 100 using control flow structures like if/else in 1 sentence. 3. Count character frequencies in a string and split/join a birthday string using dictionary in 1 sentence. 4. Find mean, median, mode of a list and find duplicate elements in a list using a function in 1 sentence. 5. Demonstrate addition and multiplication of 2D matrices using

Uploaded by

Jarrar Malik
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/ 26

UNIVERSITY OF ENGINEERING AND TECHNOLOGY TAXILA

SUBMITTED TO:
Engr. Asma Shafi
SUBMITTED BY:
Muhammad Jarrar Mehdi
(22-TE-04)
OBJECTIVE:
OOP Lab Manuals.

DEPARTMENT OF TELECOM ENGINEERING UET TAXILA

DATED: 13-07-2023
WEEK - 1 BASICS
OF PYTHON

OBJECTIVE:
a. To purposefully raise Indentation Error and Correct it.
b. To compute distance between two points taking input from the user (Pythagorean Theorem).
c. To take numbers as command line arguments and print its sum.

RESOURCE:
Python 3.7.3

PROGRAM LOGIC:

Compute distance between two points:

1. Read number of terms.


2. Send values to mathematical sqrt function
3. Print the distance

Sum of two numbers:


1. Read two integers n1 and n2.
2. Use arithmetic operator +
3. Print the sum.

PROCEDURE:
a. Create : Open a new file in Python shell, write a program and save the program with .py extension.
b. Execute : Go to Run -> Run module (F5)

SOURCE CODE:
Script to purposefully raise Indentation Error and Correct it:
print("IARE")
print("Hyderabad")

output:
print("Hyderabad")
^
IndentationError: unexpected indent

print("IARE")
print("Hyderabad")
Output:
IARE
Hyderabad

Compute distance between two points


import math
p11 =int(input())
p12 =int(input())
p21 =int(input())
p22
=int(input())
distance = math.sqrt( ((p11-p21)**2)+((p12-
p22)**2) ) print(distance)input:0466
Output:
6.324555320336759

Sum of two numbers

import sys
a, b = sys.argv[1:2]
summ = int(a) + int(b)
print("sum is", summ)

Input:
23

Output:
sum is 5
WEEK - 2 CONTROL
FLOW

OBJECTIVES:
a. To checking whether the given number is even number or not.
b. To find the factorial of a number.
c. To print the prime numbers below 100

RESOURCE:
Python 3.7.3

PROGRAM LOGIC:
Checking whether the given number is even number or not

1. Read the number.


2. Divide the number by 2
3. Compare the reminder value
4. Display the result

Finding the factorial of a number


1. Read the number.
2. Decrement the value
3. Compare the reminder value
4. Display the result

Print the prime numbers below 100


1. Read the number.
2. Check the number prime or not
3. If yes print the number
4. If not decrement the value
5. Check the number reaches zero.
6. If not goto step2
7. End of the program.

PROCEDURE:
a. Create: Open a new file in Python shell, write a program and save the program with .py extension.
b. Execute : Go to Run -> Run module (F5)

SOURCE CODE:
Checking whether the given number is even number or not

a=int(input())
if(a%2==0):
print("Even")
else:
print("Odd")

Input:
4
Output:Even
Finding the factorial of a number

a=int(input())
k=1;
for i in range(1,a+1):
k=k*i;
print("The factorial of given number is", k)

input:
5
Output:
The factorial of given number is 120

Print the prime numbers below 100

for i in
range(2,100):
c=0;
for j in
range(1,i+1): if(i
%j==0):
c=c+1
if(c<=2):
print(i,end =" "),

Output:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
WEEK - 3
STRINGS

OBJECTIVES:

a. To implement to count the numbers of characters in the string and store them in a dictionary
data structure
b. To use split and joins methods in the string and trace a birthday with a dictionary data structure

RESOURCE:
Python 3.7.3

PROGRAM LOGIC:
Count the numbers of characters in the string

1. Read the string.


2. Count the characters
3. Display the result

PROCEDURE:
a. Create: Open a new file in Python shell, write a program and save the program with .py extension.
b. Execute : Go to Run -> Run module (F5)

SOURCE CODE:
Count the numbers of characters in the string

str1=input()
dict = {}
for n in str1:
keys =
dict.keys() if n in
keys:
dict[n] +=
1 else:
dict[n] =
1 print(dict)

Input:
Success
Output:
{'s': 3, 'u': 1, 'c': 2, 'e': 1}

Split and joins methods in the string

birthdays = {'Alice': 'Apr 1 1998', 'Bob': 'Dec 12,2001', 'Carol': 'Mar 4,2002'}
name=input()
if name in birthdays:

s=birthdays[name];
L=s.split(" ")
k="-"
L=k.join(L)
print(L + ' is the birthday of’+name)else: print('I do not have birthday information for ' + name
Input:
Alice

Output:
Apr-1-1998 is the birthday of Alice
WEEK - 4
LIST

OBJECTIVES:

a. To finding mean, median, mode for the given set of numbers in a list.
b. To function dups to find all duplicates in the list.

RESOURCE:
Python 3.7.3

PROGRAM LOGIC:

To find mean, median, mode for the given set of numbers in a list.
1. Read the elements into a list.
2. Calculate the sum of list elements.
3. Calculate the mean, median.
4. Display the result.

Function dups to find all duplicates in the list.

1. Create a list to read elements.


2. Pass the list as parameter to dup function.
3. Define function dup to identify duplicate elements in the list.
4. Return the final list to called function.
5. Display the result.

PROCEDURE:
a. Create : Open a new file in Python shell, write a program and save the program with .py extension.
b. Execute : Go to Run -> Run module (F5)

SOURCE CODE:

To find mean, median, mode for the given set of numbers in a list

from collections import Counter


n_num = [1, 2, 3, 4, 5,5]
n = len(n_num)
get_sum = sum(n_num)
mean = get_sum / n
nnum=n_num;
print("Mean / Average is: " +
str(mean)) nnum.sort()
if n % 2 == 0:
median1 = nnum[n//2]
median2 = nnum[n//2 -
1]
median = (median1 +
median2)/2 else:
median = nnum[n//2]
print("Median is: " + str(median))
data = Counter(n_num)
get_mode = dict(data)
mode = [k for k, v in get_mode.items() if v == max(list(data.values()))] if len(mode) == n: get_mode =
"No mode found"
else:
get_mode = "Mode is / are: " + ', '.join(map(str,
mode)) print(get_mode)

Output:
Mean / Average is: 3.3333333333333335
Median is: 3.5
Mode is / are: 5

Function dups to find all duplicates in the list.

def Remove(duplicate):
final_list = []
for num in duplicate:
if num not in final_list:
final_list.append(num)
return final_list

# Driver Code
duplicate = [2, 4, 10, 20, 5, 2, 20, 4]
print(Remove(duplicate))

Output:
[2, 4, 10, 20, 5]
WEEK - 5

MULTI DIMENSIONAL LIST

OBJECTIVES:
a. Write a Python script for addition of two square matrices.
b. Write a Python script for multiplication of two matrices.

RESOURCE:
Python 3.7.3

PROGRAM LOGIC:

Addition of two square matrices.


1. Create a lists to read matrix elements
2. Read the elements of to matrices add the elements
3. Store the result in third matrix.
4. Repeat steps 2 and 3 till the addition of all elements
5. Display the result

Multiplication of two matrices


1. Create a lists to read matrix elements
2. Read the elements of to matrices, multiply the elements
3. Store the result in third matrix.
4. Repeat steps 2 and 3 till the multiplication of all elements
5. Display the result.

PROCEDURE:
a. Create: Open a new file in Python shell, write a program and save the program with .py extension.
b. Execute : Go to Run -> Run module (F5)

SOURCE CODE:

Addition of two square matrices


X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]

# iterate through rows


for i in range(len(X)):
# iterate through
columns for j in
range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]

for r in
result:
print(r)
Output:
[17, 15, 4] [10, 12, 9] [11, 13, 18]
Multiplication of two matrices
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]

# iterate through rows of X


for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]

for r in result:
print(r)

Output:
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]
WEEK-6
CLASS

OBJECTIVES:

a. Find the validity of a string of parentheses, '(', ')', '{', '}', '[' and ']. These brackets must be close in
the correct order, for example "()" and "()[]{}" are valid but "[)", "({[)]" and "{{{" are invalid.
b. Get all possible unique subsets from a set of distinct integers.

RESOURCE:
Python 3.7.3

PROGRAM LOGIC:

Validity of a string of parentheses


1. Create a lists to read string of parentheses
2. Read the open,close parentheses into two lists
3. Compare the open and close list parentheses.
4. Display the result

PROCEDURE:
a. Create : Open a new file in Python shell, write a program and save the program with .py extension.
b. Execute : Go to Run -> Run module (F5)

SOURCE CODE:

open_list = ["[","{","("]
close_list = ["]","}",")"]
def check(myStr):
stack = []
for i in myStr:
if i in open_list:
stack.append(i)
elif i in close_list:
pos =
close_list.index(i) if
((len(stack) > 0) and
(open_list[pos] == stack[len(stack)-1])):
stack.pop()
else:
return "Unbalanced"
if len(stack) == 0:
return "Balanced"
string = "{[]{()}}"
print(string,"-",
check(string)) string = "[{}
{})(]" print(string,"-",
check(string))

Output:
{[]{()}} - Balanced
[{}{})(] - Unbalanced
Get all possible unique subsets from a set of distinct integers. class py_solution:
def sub_sets(self, sset):
return self.subsetsRecur([], sorted(sset))

def subsetsRecur(self, current,


sset): if sset:
return self.subsetsRecur(current, sset[1:]) + self.subsetsRecur(current + [sset[0]], sset[1:])
return [current]
print(py_solution().sub_sets([4,5,6]))

Output:
[[], [6], [5], [5, 6], [4], [4, 6], [4, 5], [4, 5, 6]]
WEEK - 7
METHODS

OBJECTIVE:
a. Create a Python class named Circle constructed by a radius and two methods which will compute
the area and the perimeter of a circle.
b. Create a Python class named Rectangle constructed by a length and width and a method which
will compute the area of a rectangle.

RESOURCE:
Python 3.7.3

PROGRAM LOGIC:

Validity of a string of parentheses


1. Create a class circle
2. Define a method to calculate radius
3. Create object to call the methods of class
4. Display the result

PROCEDURE:
a. Create: Open a new file in Python shell, write a program and save the program with .py extension.
b. Execute : Go to Run -> Run module (F5)

SOURCE CODE:

The area and the perimeter of a circle.


class Circle():
def init (self, r):
self.radius = r
def area(self):
return self.radius**2*3.14
def perimeter(self):
return 2*self.radius*3.14
NewCircle = Circle(8)
print(NewCircle.area())
print(NewCircle.perimeter())
Output:
200.96
50.24

The area of a rectangle.


class Rectangle():
def init (self, l, w):
self.length = l
self.width = w
def rectangle_area(self):
return self.length*self.width
newRectangle = Rectangle(12, 10)
print(newRectangle.rectangle_area())

Output:
120
WEEK – 8

OBJECTIVE:

Write Python program to implement constructors.

RESOURCE:
Python 3.7.3

SOURCE CODE:

class IARE:
geek = ""
def init (self):
self.geek =
"IARE"
def print_Geek(self):
print(self.geek)
obj = IARE()
obj.print_Geek()

Output:
IARE
WEEK - 9
INHERITANCE

OBJECTIVE:

Write Python program to implement inheritance

RESOURCE:
Python 3.7.3

SOURCE CODE:

class Person(object):
def init (self, name):
self.name = name
def getName(self):
return self.name
def isEmployee(self):
return False
class Employee(Person):
def isEmployee(self):
return True
emp = Person("IARE1")
print(emp.getName(), emp.isEmployee())
emp = Employee("IARE2")
print(emp.getName(), emp.isEmployee())

Output:
IARE1 False
IARE2 True
WEEK - 10
POLYMORPHISM

OBJECTIVE:

Write Python program to implement Polymorphism.

RESOURCE:
Python 3.7.3

PROGRAM LOGIC:

PROCEDURE:

a. Create : Open a new file in Python shell, write a program and save the program with .py extension.
b. Execute : Go to Run -> Run module (F5)

SOURCE CODE:

def add(x, y, z = 0):


return x + y+z
print(add(2, 3))
print(add(2, 3, 4))

Output:
5
3
WEEK - 11 OVERRIDING
MAGIC METHODS

OBJECTIVE:
Write Python program to override Magic Methods.

RESOURCE:
Python 3.7.3

PROGRAM LOGIC:

PROCEDURE:

a. Create: Open a new file in Python shell, write a program and save the program with .py extension.
b. Execute : Go to Run -> Run module (F5)

SOURCE CODE:

class Bird:
def intro(self):
print("There are many types of
birds.") def flight(self):
print("Most of the birds can fly but some
cannot.") class sparrow(Bird):
def flight(self):
print("Sparrows can
fly.") class ostrich(Bird):
def flight(self):
print("Ostriches cannot
fly.") obj_bird = Bird()
obj_spr =
sparrow() obj_ost =
ostrich()
obj_bird.intro()
obj_bird.flight()
obj_spr.intro()
obj_spr.flight()
obj_ost.intro()
obj_ost.flight()

Output:
New Delhi is the capital of India.
Hindi the primary language of
India. India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of
USA. USA is a developed country.
WEEK - 12

EVENT-DRIVEN PROGRAMMING

OBJECTIVE:
Write Python program to create a simple calculator, where the user will enter a number in a text field,
and either add it to or subtract it from a running total, which we will display. We will also allow the user to
reset the total.

RESOURCE:
Python 3.7.3

PROCEDURE:
a. Create : Open a new file in Python shell, write a program and save the program with .py extension.
b. Execute : Go to Run -> Run module (F5)

SOURCE CODE:
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:
")) if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")

Input and Output:


Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4):1
Enter first number: 3
Enter second number:
43+4=7
PRE LAB VIVA QUESTIONS:
a. What is the predefined function required?
b. Which file we are importing to execute?
c. Explain the importance function declaration?

POST LAB VIVA QUESTIONS:


a. Explain the object creation in python?
b. Explain the exception handling?
c. Explain try catch in python?

You might also like