University of delhi
Vivekananda college
GE - Object Oriented
Programming with
Python
Subject code-
2344570001
Practical File
Student name - Akanksha
University roll no. - 25084505015
Q 1- Write a program to find the roots of a quadratic
equation.
Ans 1-
import math
a = float(input("Enter the first number for your equation (a): "))
b = float(input("Enter the second number for your equation (b): "))
c = float(input("Enter the third number for your equation (c): "))
d = b**2 - 4*a*c
if a == 0:
print("Error: 'a' cannot be zero (not a quadratic equation).")
elif d < 0:
print("No real solutions (discriminant is negative)")
else:
x1 = (-b + [Link](d))/(2*a)
x2 = (-b - [Link](d))/(2*a)
print("The solutions are:")
print("x1 =", x1)
print("x2 =", x2)
Output
Q 2- Write a program to accept a number ‘n’ and
a. Check if ’n’ is prime
b. Generate all prime numbers till ‘n’
c. Generate first ‘n’ prime numbers
This program may be done using functions.
Ans 2-
(a)
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
n = int(input("Enter n: "))
print("Prime:", is_prime(n))
Output
(b)
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
n = int(input("Enter n: "))
print("Primes till n:", [i for i in range(2, n+1) if is_prime(i)])
Output
(c)
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
n = int(input("Enter n: "))
primes = []
num = 2
while len(primes) < n:
if is_prime(num):
[Link](num)
num += 1
print("First n primes:", primes)
Output
Q 3- Write a program to create a pyramid of the character
‘*’ and a reverse pyramid
Ans 3-
n = int(input("Enter number of rows: "))
print("Pyramid:")
for i in range(1, n+1):
print("*" * i)
print("Reverse Pyramid:")
for i in range(n, 0, -1):
print("*" * i)
Output
Q 4- Write a program that accepts a character and
performs the following:
a. print whether the character is a letter or numeric digit
or a special character.
b. if the character is a letter, print whether the letter is
uppercase or lowercase
c. if the character is a numeric digit, prints its name in
text (e.g., if input is 9, output is NINE)
Ans 4-
x = input("Enter a character: ")
if [Link]():
print("It is a letter.")
if [Link]():
print("Uppercase letter")
else:
print("Lowercase letter")
elif [Link]():
print("It is a digit.")
num_names =
["ZERO","ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE"]
print(num_names[int(x)])
else:
print("Special character")
Output
Q 5- Write a program to perform the following operations
on a string
a. Find the frequency of a character in a string.
b. Replace a character by another character in a string.
c. Remove the first occurrence of a character from a
string.
d. Remove all occurrences of a character from a string.
Ans 5-
x = input("Enter string: ")
y = input("Enter character from your string: ")
z = input("Enter replacement character: ")
# a
print("Frequency:", [Link](y))
# b
print("Replace:", [Link](y, z))
# c
print("Remove first occurrence:", [Link](y, "", 1))
# d
print("Remove all occurrences:", [Link](y, ""))
Output
Q 6- Write a program to swap the first n characters of two
strings.
Ans 6-
str_1 = input("Enter string 1: ")
str_2 = input("Enter string 2: ")
n = int(input("Enter the length of string upto which you want the
characters to step: "))
s1_new = str_2[:n] + str_1[n:]
s2_new = str_1[:n] + str_2[n:]
print("String 1 after swap:", s1_new)
print("String 2 after swap:", s2_new)
Output
Q 7- Write a function that accepts two strings and returns
the indices of all the occurrences of the second string in
the first string as a list. If the second string is not present
in the first string then it should return -1.
Ans 7-
def find_all(a, b):
indices = []
i = [Link](b)
while i != -1:
[Link](i)
i = [Link](b, i+1)
return indices if indices else -1
s1 = input("Enter main string: ")
s2 = input("Enter substring: ")
print(find_all(s1, s2))
Output
Q 8- Write a program to create a list of the cubes of only
the even integers appearing in the input list (may have
elements of other types also) using the following:
a. 'for' loop
b. list comprehension
Ans 8-
(a)
list = [1, 2, 3, 4, 5]
even_list = []
for x in list:
if type(x) == int and x % 2 == 0:
even_list.append(x**3)
print(even_list)
(b)
list = [1, 2, 3, 4, 5]
print([x**3 for x in list if type(x) == int and x % 2 == 0])
Output
Q 9- Write a program to read a file and
a. Print the total number of characters, words and lines in
the file.
b. Calculate the frequency of each character in the file.
Use a variable of dictionary type to maintain the count.
c. Print the words in reverse order.
d. Copy even lines of the file to a file named ‘File1’ and
odd lines to another file named ‘File2’.
Ans 9-
# Reading the file
with open("[Link]", "r") as f:
lines = [Link]()
# (a)
total_lines = len(lines)
total_chars = 0
total_words = 0
for line in lines:
total_chars += len(line)
total_words += len([Link]())
print("Total Characters:", total_chars)
print("Total Words:", total_words)
print("Total Lines:", total_lines)
# (b)
freq = {}
for line in lines:
for ch in line:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
print("Character Frequency:")
print(freq)
# (c)
all_words = []
for line in lines:
all_words.extend([Link]())
print("Words in Reverse Order:")
print(all_words[::-1])
# (d)
with open("[Link]", "w") as f1, open("[Link]", "w") as f2:
for i in range(len(lines)):
if (i + 1) % 2 == 0: # even line number
[Link](lines[i])
else: # odd line number
[Link](lines[i])
Output
Q 10- Write a function that prints a dictionary where the
keys are numbers between 1 and 5 and the values are
cubes of the keys.
Ans 10-
def cube_dict():
d = {}
for i in range(1, 6):
d[i] = i**3
print(d)
cube_dict()
Output
Q 11- Consider a tuple t1=(1, 2, 5, 7, 9, 2, 4, 6, 8, 10).
Write a program to perform following operations:
a. Print half the values of the tuple in one line and the
other half in the next line.
b. Print another tuple whose values are even numbers in
the given tuple.
c. Concatenate a tuple t2=(11,13,15) with t1.
d. Return maximum and minimum value from this tuple
Ans 11-
t1=(1,2,5,7,9,2,4,6,8,10)
# a
print(t1[:5])
print(t1[5:])
# b
print(tuple(x for x in t1 if x%2==0))
# c
t2=(11,13,15)
print(t1+t2)
# d
print(max(t1),min(t1))
Output
Q 12- Define a class Employee that stores information
about employees in the company. The class should contain
the following:
(i) data members- count (to keep a record of all the
objects being created for this class) and for every
employee: an employee number, Name, Dept, Basic, DA
and HRA.
(ii) function members:
a. __init__ method to initialize and/or update the members.
Add statements to ensure that the program is terminated
if any of Basic, DA and HRA is set to a negative value.
b. function salary, that returns salary as the sum of Basic,
DA and HRA.
c. __del__ function to decrease the number of objects
created for the class.
d. __str __ function to display the details of an employee
along with the salary of an employee in a proper format.
Ans 12-
class Employee:
count=0
def __init__(self,num,name,dept,basic,da,hra):
if basic<0 or da<0 or hra<0:
raise ValueError("Negative salary component!")
[Link]+=1
[Link]=num; [Link]=name; [Link]=dept
[Link]=basic; [Link]=da; [Link]=hra
def salary(self): return [Link]+[Link]+[Link]
def __del__(self): [Link]-=1
def __str__(self):
return f"{[Link]} {[Link]} {[Link]()}"
e=Employee(1,"A","CS",1000,200,300)
print(e)
Output
Q 13- Write a program to define a class "2DPoint" with
coordinates x and y as attributes. Create relevant
methods and print the objects. Also define a method
distance to calculate the distance between any two point
objects.
Ans 13-
import math
class Point2D:
def __init__(self,x,y): self.x=x; self.y=y
def distance(self,p):
return [Link]((self.x-p.x)**2 + (self.y-p.y)**2)
p1=Point2D(0,0); p2=Point2D(3,4)
print([Link](p2))
Output
Q 14- Inherit the above class to create a "3Dpoint" with
additional attribute z. Override the method defined in
"2DPoint" class, to calculate distance between two points
of the "3DPoint" class.
Ans 14-
import math
class Point2D:
def __init__(self,x,y): self.x=x; self.y=y
def distance(self,p):
return [Link]((self.x-p.x)**2 + (self.y-p.y)**2)
p1=Point2D(0,0); p2=Point2D(3,4)
class Point3D(Point2D):
def __init__(self,x,y,z):
super().__init__(x,y); self.z=z
def distance(self,p):
return [Link]((self.x-p.x)**2 + (self.y-p.y)**2 + (self.z-
p.z)**2)
a=Point3D(0,0,0); b=Point3D(1,2,2)
print([Link](b))
Output
Q 15- Write a program to accept a name from a user. Raise
and handle appropriate exception(s) if the text entered by
the user contains digits and/or special characters.
Ans 15-
name = input("Enter your name: ")
try:
if not [Link]():
raise ValueError("Name can contain only letters.")
print("Name accepted:", name)
except ValueError as e:
print("Error:", e)
Output