Oops Lab File
Oops Lab File
PRACTICAL FILE
Object Oriented Concepts and Python
Programming
CSE – 104 P
Code :-
li=[5,7,54,36]
tup=(3,"java",75,"python")
print(li)
print(dic)
print(tup)
print(str)
print(type(li))
print(type(dic))
print(type(tup))
print(type(str))
Output :-
Program - 2
Aim : WAP to perform operations- Addition(+), Substraction(-),
Multliplication(*), Division(/), Integer Division(//), Exponential(**).
Code :-
a=5
b=7
c=a+b
d=b-a
e=a*b
f=b/a
g=a//b
h=a**b
print("Addition=",c)
print("Substraction=",d)
print("Multiplicatio=",e)
print("Division=",f)
print("Integer Division=",g)
print("Exponential=",h)
Output :-
Program - 3
Aim : WAP to find a square of a number entered by user.
Code :-
num=int(input("Enter the number:"))
print("number =",num)
sqr=num*num
Output :-
Program - 4
Aim : WAP to swap two numbers.
Code :-
a=50
b=60
print("a=",a)
print("b=",b)
c=0
c=a
a=b
b=c
print("a=",a)
print("b=",b)
Output :-
Program - 5
Aim : WAP to convert Celcius into Fahrenheit and vice-versa.
Code :-
fahrenheit=9/5*(celcius_num)+32
celcius=5/9*(fahr_num-32)
print("Celcius value=",celcius_num)
print("Fahrenheit value=",fahr_num)
print("Fahrenheit temperature=",fahrenheit)
print("Celcius temperature=",celcius)
Output :-
Lab – 2
(If – Else loop)
Program - 1
Aim : WAP to check whether a triangle is equilateral, isosceles or
scalene.
Code :-
a=input("Enter the side of triangle:")
b=input("Enter the side of triangle:")
c=input("Enter the side of triangle:")
print("a=",a)
print("b=",b)
print("c=",c)
if(a==b and b==c and a==c):
print("Triangle is equilateral")
elif(a==b or b==c or a==c):
print("Triangle is isosceles")
else:
print("Triangle is scalene")
Output :-
Program - 2
Aim : WAP to check whether a person is eligible for voting or not.
Code :-
print("age=",age)
if age<=18:
else:
Output :-
Program - 3
Aim : WAP to grade the students according to their marks.
Else: Grade D
Code :-
print("marks=",marks)
print("Grade A")
print("Grade B")
print("Grade C")
else:
print("Grade D")
Output :-
Program - 4
Aim : WAP to find the maximum, minimum and middle of three numbers
input by user.
Code :-
else:
Output :-
Program - 5
Aim : WAP to make a calculator using if-else loop performing operations
i.e. (+), (-), (*), (/), (//), (**).
Code :-
a=int(input("enter the first number:"))
if op == "+":
result=a+b
elif op == "-":
result=a-b
elif op == "*":
result=a*b
elif op == "/":
result=a/b
elif op == "//":
result=a//b
elif op == "**":
result=a**b
else:
result="invalid operator"
print("result=",result)
Output :-
Lab – 3
(For and While loop)
Program - 1
Aim : Write a program to print table of an integer number input
by user.
Code :-
num=int(input("enter the number:"))
print("Table of ",num)
for i in range(1,11):
print(num,"X",i,"=",num*i)
Output :-
Program - 2
Aim : Write a program to print the factorial of a number.
Code :-
num=int(input("enter the number:"))
fact=1
for i in range(1,num+1):
fact=fact*i
print("Factorial =",fact)
Output :-
Program - 3
Aim : Write a program to print the fibonacci series upto a given
number.
Code :-
n=int(input("enter the number:"))
a=0
b=1
sum=0
print("Fibonacci series :")
while(sum<=n):
print(sum)
a=b
b=sum
sum=a+b
Output :-
Program - 4
Aim : Write a program to print the patterns.
Code :-
(a) for i in range(1,5):
for j in range(1,i+1):
print(j,end=" ")
print("\n")
Output :-
Output :-
Program - 6
Aim : Write a program using a while loop that asks the user for a
number, and prints a countdown from that number to zero.
Code :-
num=int(input("enter the number:"))
while(num>=0):
print(num)
num=num-1
Output :-
Program - 7
Aim : Write a program to perform linear search opf a program.
Code :-
li=[2,4,3,8,6,9]
print("li =",li)
val=int(input("enter the value which is to be search:"))
pos=0
for i in range(0,6):
if(li[i]==val):
pos=i
print("position =",pos)
print("search successful")
if(pos==0):
print("search unsuccessful")
Output :-
Lab – 4
(Strings)
Program - 1
Aim : Write a program to input three strings from a user using
only one input() command and print the concatenated string.
Code :-
str1=input("enter the string value :")
str2=input("enter the string value :")
str3=input("enter the string value :")
str = (str1 + str2 + str3).split(",")
print("str = ",str)
Output :-
Program - 2
Aim : Write a program to reverse the string using (1) string
slicing and (2) reverse() function.
Code :-
str1 = "Hello python programmer"
print("str = ",str1)
print("Reverse str using slicing :",str1[::-1])
rev_str = "".join(reversed(str1))
print("Reverse str using reverse() function :",rev_str)
Output :-
Program - 3
Aim : Write a python program to demostrate various ways of
accessing the strings.
(1) By using indexing (both positive and negative)
(2) By using slice operator.
Code :-
str1 = "Hello"
print("string = ",str1)
print("string using positive indexing :",str1[0:5])
print("string using negative indexing :",str1[-5:])
print("string using slicing method :",str1[::1])
Output :-
Program - 4
Aim : Demonstrate the following functions/methods which
operates on strings in python with suitable examples:
i.) len() ii.)strip() iii.)rstrip() iv.)lstrip() v.)find()
vi.)index() vii.)count() viii.)replace() ix.)split() x.)upper()
xi.)lower() xii.)swapcase() xiii.)title() xiv.)capitalize()
xv.)startswith() xvi.)endswith().
Code :-
str1 = "Hello Python"
print("string1 = ",str1)
print("Length of string using len() method :",len(str1))
str2 = " hello python"
print("String2 = ",str2)
print("strip of string :",str2.strip())
print("rstrip of string :",str2.rstrip("on"))
print("lstrip of string :",str1.lstrip("He"))
print("Find method :",str1.find("Hello"))
print("Index of string element 'p' :",str2.index("p"))
print("Count 'o' in string :",str1.count("o"))
print("Replace hello with hi in string:",str1.replace("Hello","Hi"))
print("Split() function in python :",str1.split())
print("Upper function in python :",str1.upper())
print("Lower function in python :",str1.lower())
print("Swapcase function in python :",str1.swapcase())
str3 = "hello PYTHON programmer"
print("String3 =",str3)
print("Title function in python :",str3.title())
print("Capitalize function in python :",str3.capitalize())
print("Startswith function in python :",str3.startswith("hello"))
print("Endswith function in python :",str3.endswith("hello"))
Output :-
Program - 5
Aim : Write a program to find the length of a string using
(a)inbuilt function len() and (b) for loop.
Code :-
def findlength(str1):
counter=0
for i in str1:
counter += 1
return counter
str1 = "Hello python programmer"
print("String =",str1)
print("Length of string using len() function :",len(str1))
print("Length of string using for loop :",findlength(str1))
Output :-
Lab – 5
(Lists)
Program - 1
Aim : Write a program to input all the elements of a list and
multiply them.
Code :-
li=[23,4,7,12,8,3]
print("List =",li)
mul=1
for i in range(0,6):
mul = mul * li[i]
print("Multiplication =",mul)
Output :-
Program - 2
Aim : write a program to find the maximum and second
maximum elements of a list.
Code :-
def find_len(li):
length = len(li)
li.sort()
print("Maximum value of list :",li[length-1])
print("Second maximum value of list :",li[length-2])
li=[23,56,12,89,76,69]
print("List =",li)
largest = find_len(li)
Output :-
Program - 3
Aim : Write a program to input 10 elements in a list with 3
duplicate elements. Output a list after removing all duplicate
elements from a list.
Code :-
def Remove(duplicate):
final_list = []
for num in duplicate :
if num not in final_list:
final_list.append(num)
return final_list
duplicate = [2,5,8,5,23,2,63,8,2,5]
print("List with duplicate value =",duplicate)
print("List without duplicate value =",Remove(duplicate))
Output :-
Program - 4
Aim : Write a program to print two lists comprising odd and even
numbers seperated from a list.
Code :-
print("Number =")
for num in range(1, 51):
print(num,end=" ")
print("\n")
print("even number:")
for even in range(2,51,2):
print(even,end=" ")
print("\n")
print("odd number:")
for odd in range(1,51,2):
print(odd,end=" ")
Output :-
Program - 5
Aim : Write a program to append one list to another.
Code :-
list1 = [5,6,7,8]
print("List1 =",list1)
another_list = [1,2,3,4]
print("Another list =",another_list)
list1.append(another_list)
print("List after append =",list1)
Output :-
Program - 6
Aim : Write a program to check if a particular element exists in a
list or not.
Code :-
list1 = [56,35,27,88,19]
print("List =",list1)
val=int(input("Enter the value to be searched :"))
pos=-1
for i in range(0,5):
if list1[i] == val:
pos=i
print("Position =",pos)
print("Element is found in the list")
if pos==-1:
print("Element is not found in the list")
Output :-
Program - 7
Aim : Write a program to implement following built-in functions
on a list : (i.)insert() (ii.)remove() (iii.)pop() (iv.)reverse()
(v.)count() (vi.)min() (vii.)max() (viii.)sort().
Code :-
list1 = [24,36,77,98,11,29,11,20,93,11]
print("List =",list1)
list1.insert(3,56)
print("List after adding 56 at index(3) :",list1)
list1.remove(24)
print("List after removing element(24) :",list1)
list1.pop(2)
print("List after using pop method :",list1)
list1.reverse()
print("Reverse of a list :",list1)
count = list1.count(11)
print("Counting of element(11) using count() method :",count)
max = max(list1)
print("Maximum value in list :",max)
min = min(list1)
print("Minimum value in list :",min)
list1.sort()
print("Sorted list :",list1)
Output :-
Lab – 6
(Dictionaries)
Program - 1
Aim : WAP to create a dictionary and check if a given key
already exists in dictionary.
Code :-
dict = {3:"Hello", 7:"Python", 11:"Programmer"}
print("Dictionary =",dict)
dict_key = int(input("Enter the key number:"))
print("Dict_key =",dict_key)
if dict_key in dict:
print("Key exist in the dictionary")
else:
print("Key does not exist in the dictionary")
Output :-
Program - 2
Aim : WAP to input the elements in dictionary and find the mean
of all the values present in a dictionary.
Code :-
n = int(input("Enter the number of elements :"))
d={}
for i in range(n):
key = input("Enter the key value :")
value = int(input("Enter the value :"))
d[key]=value
print("Dictionary =",d)
length = len(d)
print("length =",length)
sum=0
for value in d.values():
sum += value
mean = sum/length
print("Mean =",mean)
Output :-
Program – 3
Aim : WAP to concatenate the following dictionaries to create a
new one.
dict1 = {1:20, 2:40}
dict2 = {3:60, 4:80}
dict3 = {5:100, 6:120}
Code :-
dict1 = {1:20, 2:40}
dict2 = {3:60, 4:80}
dict3 = {5:100, 6:120}
dict = {}
for d in (dict1, dict2, dict3):
dict.update(d)
print("dict = ",dict)
Output :-
Program – 4
Aim : WAP to sort the dictionary by keys and values.
Code :-
d = {3:45, 7:23, 1:55, 4:39}
print("Dictionary =",d)
sorted_dict1 = sorted(d.keys())
print("Sorted dictionary by keys :",sorted_dict1)
sorted_dict2 = sorted(d.items())
print("Sorted dictionary by values :",sorted_dict2)
Output :-
Program – 5
Aim : WAP to sum all the values of a dictionary input by user.
Code :-
n = int(input("Enter the number of elements :"))
d={}
for i in range(n):
key = input("Enter the key value :")
value = int(input("Enter the value :"))
d[key]=value
print("Dictionary =",d)
sum=0
for value in d.values():
sum += value
print("Sum =",sum)
Output :-
Lab – 7
(Functions and Recursion)
Program - 1
Aim :
(a) Write a python program to calculate factorial of a number
using function.
Code :-
num = int(input("enter the value of number :"))
fact=1
for i in range(1,num+1):
fact = fact*i
print("Factorial of ",num,"is",fact)
Output :-
(b) Write a python program to calculate factorial of a number
using recursion.
Code :-
def fact(n):
if n==0 or n==1:
return 1
else:
return n*fact(n-1)
n = int(input("Enter the value of number :"))
print("Factorial of ", n, "is",fact(n))
Output :-
Program - 2
Aim :
(a) Write a python program to find the fibonacci series upto a
given number using function.
Code :-
n=int(input("enter the number:"))
a=0
b=1
sum=0
print("Fibonacci series :")
while(sum<=n):
print(sum)
a=b
b=sum
sum=a+b
Output :-
(b) Write a python program to find the fibonacci series upto a
given number using recursion.
Code :-
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms=int(input("enter the value of n terms :"))
if nterms<=0:
print("Please enter a positive number")
else:
("Fibonacci series :")
for i in range(nterms):
print(recur_fibo(i))
Output :-
Program - 3
Aim :
(a) Write a python program to find the sum of first N natural
numbers using function.
Code :-
N =int(input("Enter the value:"))
print("Natural numbers:")
sum=0
for i in range(1,N+1):
print(i)
sum = sum + i
print("Sum of ",N, "natural number :",sum)
Output :-
(b) Write a python program to find the sum of first N natural
numbers using recursion.
Code :-
def recur_sum(n):
if n<=1:
return n
else:
return n + recur_sum(n-1)
num=int(input("enter the number:"))
print("Natural numbers :")
for i in range(1,num+1):
print(i)
if num<0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(num))
Output :-
Program - 4
Aim :
(a) Write a python program to find the GCD of a number using
function.
Code :-
import math
num1 = int(input("enter the number1 :"))
num2 = int(input("enter the number2 :"))
print("The GCD of numkber1 and number2 is :",end=" ")
print(math.gcd(num1,num2))
Output :-
(b) Write a python program to find the GCD of a number using
recursion.
Code :-
def hcfnaive(a,b):
if (b==0):
return abs(a)
else:
return hcfnaive(b,a%b)
num1 = int(input("enter the number1 :"))
num2 = int(input("enter the number2 :"))
print("The GCD of numkber1 and number2 is :",end=" ")
print(hcfnaive(num1,num2))
Output :-
Program - 5
Aim :
(a) Write a python program to find the power of a number using
function.
Code :-
def calculatepower(N,X):
P=1
for i in range(1,X+1):
P=P*N
return P
N,X = 2,3
print("The power of number :",calculatepower(N,X))
N,X = 3,4
print("The power of number :",calculatepower(N,X))
Output :-
(b) Write a python program to find the power of a number using
recursion.
Code :-
def power(N,P):
if P==0:
return 1
return (N*power(N,P-1))
if __name__ == '__main__':
N=5
P=2
print("Power of number using recursion :",power(N,P))
Output :-
Lab – 8
(Tuples)
Program - 1
Aim : Write a python program to test if a variable is a list or tuple
or a set.
Code :-
x=[3,6,9,12,15,18]
print("X=",x)
if type(x) is list:
print("x is a list")
elif type(x) is tuple:
print("x is a tuple")
elif type(x) is set:
print("x is a set")
else:
print("It is not a set, tuple and list")
Output :-
Program - 2
Aim : Write a python program to sort the elements of a tuple.
Code :-
tup=(23,1,5,89,4,3,54,12)
print("Tuplt =",tup)
sorted_=tuple(sorted(tup))
print("Sorted tuple =",sorted_)
print(type(sorted_))
Output :-
Program - 3
Aim : Write a python program which accepts a sequence of semi-
colan seperated numbers from user and generate a list and a tuple
with those numbers.
Code :-
values = input("Input some comma seperated numbers :")
list = values.split(",")
tuple = tuple(list)
print("List =",list)
print("Tuple =",tuple)
Output :-
Program - 4
Aim : Write a program to print the multiplication of the elements
of a tuple.
Code :-
tup=(2,6,1,4,8,21,43)
print("Tuple=",tup)
mul=1
for i in range(0,7):
mul=mul*tup[i]
print("Multiplication value=",mul)
Output :-
Program - 5
Aim : Write a program to check if the user input element is
present in a tuple or not.
Code :-
tup=(23,54,12,65,78,94,11,5)
print("Tuple =",tup)
val=int(input("enter the value to be searched:"))
pos=-1
for i in range(0,8):
if tup[i]==val:
pos=i
print("position =",pos)
print("The element is present in the tuple")
if pos==-1:
print("The element is not present in the tuple")
Output :-
Lab – 9
(OOPS concepts)
Program - 1
Aim : Write a python program to create a class student, use
_inti_() function to store the name, age and ID of two students.
Create a function display() to print the details of two students.
Code :-
class Student_:
def _init_(self, name, age, student_id):
self.name = name
self.age = age
self.student_id = student_id
def display(self):
print("Name:", self.name)
print("Age:", self.age)
print("Student ID:", self.student_id)
Output :-
Program - 2
Aim : Write a python program to create a class Area. Implement
the concept of method overloading to find the area of rectangle if
a and b are not None, and area of square if either a or b is None
else nothing.
Code :-
class Area:
def find_area(self, a=None, b=None):
if a is not None and b is not None:
return self.rectangle_area(a, b)
elif a is not None and b is None:
return self.square_area(a)
else:
print("No valid parameters provided.")
def rectangle_area(self, length, breadth):
return length * breadth
def square_area(self, side):
return side * side
# Example usage:
area_calculator = Area()
l=int(input("enter the length value :"))
b=int(input("enter the breadth value :"))
s=int(input("enter the side of square value :"))
print("Area of rectangle:", area_calculator.find_area(l, b))
print("Area of square:", area_calculator.find_area(s))
print("No parameters:", area_calculator.find_area())
Output :-
Program - 3
Aim : Write a python program to create a base class Person with
getName() and setName() methods. Create a derieved class
student inhereted from Person with setAge() and getAge()
methods. Ask the user to input the details of 2 students and print
the same, by calling the methods on object.
Code :-
class Person:
def _init_(self):
self.name = ""
def getName(self):
return self.name
def setName(self, name):
self.name = name
class Student(Person):
def _init_(self):
super()._init_()
self.age = 0
def setAge(self, age):
self.age = age
def getAge(self):
return self.age
# Input details of students
students = []
for i in range(2):
student = Student()
name = input("Enter name of student {}: ".format(i + 1))
age = int(input("Enter age of student {}: ".format(i + 1)))
student.setName(name)
student.setAge(age)
students.append(student)
# Print details of students
print("\nDetails of Students:")
for i, student in enumerate(students):
print("Student {}: Name - {}, Age - {}".format(i + 1,
student.getName(), student.getAge()))
Output :-
Program - 4
Aim : Write a python program to implement the concept of
operator overloading, where the operator is ‘greater than’ which
compares the age of two students and print the result of the same.
Code :-
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __gt__(self, other):
return self.age > other.age
# Input details of two students
name1 = input("Enter first student's name: ")
age1 = int(input("Enter first student's age: "))
name2 = input("Enter second student's name: ")
age2 = int(input("Enter second student's age: "))
# Create student objects
student1 = Student(name1, age1)
student2 = Student(name2, age2)
# Compare ages using the '>' operator
if student1 > student2:
print(f"{student1.name} is older than {student2.name}.")
elif student1.age == student2.age:
print("Both students are of the same age.")
else:
print(f"{student2.name} is older than {student1.name}.")
Output :-
Lab – 10
(GUI concepts)
Aim : Write a python program to make a project on weigth
converter using Graphic User Interface (GUI).
Code :-
from tkinter import *
# Creating a GUI Window
window = Tk()
def from_kg():
gram = float(e2_value.get())*1000
pound = float(e2_value.get())*2.20462
ounce = float(e2_value.get())*35.274
t1.delete("1.0",END)
t1.insert(END, gram)
t2.delete("1.0", END)
t2.insert(END, pound)
t3.delete("1.0", END)
t3.insert(END, ounce)
e1 = Label(window, text="Input the weight in KG")
e2_value = StringVar()
e2 = Entry(window, textvariable=e2_value)
e3 = Label(window, text="Gram")
e4 = Label(window, text="Pound")
e5 = Label(window, text="Ounce")
t1 = Text(window, height=5, width=30)
t2 = Text(window, height=5, width=30)
t3 = Text(window, height=5, width=30)
b1 = Button(window, text="Convert", command=from_kg)
e1.grid(row=0, column=0)
e2.grid(row=0, column=1)
e3.grid(row=1, column=0)
e4.grid(row=1, column=1)
e5.grid(row=1, column=2)
t1.grid(row=2, column=0)
t2.grid(row=2, column=1)
t3.grid(row=2, column=2)
b1.grid(row=0, column=2)
window.mainloop()
Output :-