Ruchi Python
Ruchi Python
Course: MCA
–‘B’
ERP ID: 0241MCA281
print("Hello World!")
quotient = a // b
remainder = a % b
print("Quotient:", quotient)
print("Remainder:", remainder)
average = (a + b + c) / 3
print("The average is:", average)
marks = []
for i in range(5):
total = sum(marks)
print("Percentage:", percentage)
square_area = side ** 2
s = (a + b + c) / 2 # Semi-perimeter
9. Write a program to find the volume and surface area of cube, cuboids
and cylinder.
# Cube
cube_volume = side ** 3
cube_surface_area = 6 * (side ** 2)
# Cuboid
length = float(input("Enter the length of the cuboid: "))
# Cylinder
# Cone
# Trapezium
trapezium_area = 0.5 * (a + b) * h
# Rhombus
# Parallelogram
12. Write a program to find the perimeter of a circle, rectangle and triangle.
# Circle
# Rectangle
# Triangle
triangle_perimeter = a + b + c
simple_interest = (P * R * T) / 100
C = (F - 32) * 5 / 9
print("Temperature in Celsius:", C)
16. Write a program to swap the values of two variables with and
without using third variable.
temp = a
a=b
b = temp
a=a+b
b=a-b
a=a-b
a=8
b=3
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)
a=8
b=3
print("a == b:", a == b)
print("a != b:", a != b)
a=8
b=3
a += b
print("After a += b:", a)
a -= b
print("After a -= b:", a)
a *= b
print("After a *= b:", a)
a /= b
print("After a /= b:", a)
a //= b
a %= b
print("After a %= b:", a)
a **= b
a=8
b=3
a=8
b=3
result_and = a & b
result_or = a | b
result_xor = a ^ b
result_not_a = ~a
result_left_shift = a<<1
result_right_shift = b>>1
a=10
b=10
c=15
d=a
print(a is b) # Output : True
print(a is c) # Output : False
print(a is d) # Output : True
print(a is not c) # Output : True
print(a is not d) # Output : False
23. Write a program to Swap the Contents of two Numbers using Bitwise
XOR Operation
import math
n=int(input(“Enter the Number :”))
print(“Square of the number”,n,”is”,n**2)
28. Python program to display your details like name, age, and address in
three different lines.
name=”Sapna”
age=22
address=Ara,Bihar
print(“Name : ”,name)
print(“Age : ”,age)
print(“Address : ”,address)
29. Python program to compute the distance between the points (x1, y1)
and (x2, y2).
import math
x1,y1=map(float,input(“Enter the coordinates of the 1st
point”).split())
x2,y2=map(float,input(“Enter the coordinates of the 2nd
point”).split())
distance=math.sqrt((x2-x1)**2 +(y2-y1)**2)
print(f”The distance between the points ({x1},{y1}) and ({x2},{y2}) is :
{distance: .2f}”)
num_int = 10
num_float = 5.5
result = num_int +num_float
print(“Implicity Type Conversion: ”)
print(f“Integer: {num_int}, Float: {num_float} ”)
print(f“Result (int+float): {result} (Type : {type(result)}) ”)
num_str= “25”
num_int=10
print(“Explicit Type Conversion: ”)
print(f”String before conversion: {num_str} (Type: {type(num_str)})”)
num_str_to_int=int(num_str)
result_explicit= num_int +num_str_to_int
print(f”Result (int +converted int): {result_explicit} (Type:
{type(result_explicit)})”)
result= -9+9-8*6%8-int(19/10/2)|12&14
print(f”The Result of the expression is: {result}”)
org_str=input(“Enter a String: ”)
rev_string= org_string[::-1]
print(f”Original String: {org_string}”)
print(f”Reverse String: {rev_string}”)
34. WAP to develop a new string has even position characters of given
string. Ex: input: “GOKUGOHAN”, Output: “GKGHN”
org_str=input(“Enter a String: ”)
even_string= org_string[1::2]
print(f”Original String: {org_string}”)
print(f”String with even position : {even_string}”)
Conditional statement
35. Write a program to Accept two Integers and Check if they are Equal.
38. Write a program to find the greatest of three numbers using else if
ladder.
39. Write a program to find the greatest of three numbers using Nested if.
41. Write a program to check weather an entered year is leap year or not.
char=input(“Enter a character: ”)
vowels=”AEIOUaeiou”
if(‘A’<=char <=’Z’) or (‘a’<= char <=’z’):
for vowel in vowels:
if char == vowel:
print(”The entered character is a vowel”)
else:
print(“The entered character is a consonant”)
import math
a= float(input(“Enter the coefficient a: ”))
b= float(input(“Enter the coefficient b: ”))
c= float(input(“Enter the coefficient c: ”))
d=b**2 – 4*a*c
if d>0:
root1=(-b + math.sqrt(d))/(2*a)
root2=(-b - math.sqrt(d))/(2*a)
print(f”The roots are real and distinct ”)
elif d ==0 :
root = -b/(2*a)
print(f”The roots are real and equal ”)
else:
real=-b/(2*a)
imag=math.sqrt(abs(d))/(2*a)
print(f”The roots are complex ”)
46. Write a program to print day according to the day number entered
by the user.
47. Write a program to print color name, if user enters the first letter of
the color name.
if letter == ‘r’
print(“Red”)
elif letter == ‘g’
print(“Green”)
elif letter == ‘b’
print(“Blue”)
elif letter == ‘y’
print(“Yellow”)
elif letter == ‘o’
print(“Orange”)
elif letter == ‘v’
print(“Violet”)
elif letter == ‘w’
print(“White”)
elif letter == ‘b’
print(“Black”)
else:
print(“No color found for that letter.”)
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice (1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
result = num1 + num2
print(f"The result is: {result}")
elif choice == '2':
result = num1 - num2
print(f"The result is: {result}")
elif choice == '3':
result = num1 * num2
print(f"The result is: {result}")
elif choice == '4':
if num2 != 0:
result = num1 / num2
print(f"The result is: {result}")
else:
print("Error! Division by zero.")
else:
print("Invalid input!")
49. Write a menu driven program for calculating area of different
geometrical figures such as circle, square, rectangle, and triangle.
50. WAP that accepts the marks of 5 subjects and finds the percentage
marks obtained by the student. It also prints grades according to the
following criteria: Between 90-100% Print 'A', 80-90% Print 'B', 60-80%
Print 'C', 50- 60% Print 'D', 40-50% Print 'E', Below 40% Print 'F’.
5 X 2 = 10
5 X 3 = 15
Num=5
print(f”Multiplication table of {Num}:”)
for I in range(1,11):
print(f”{Num} X {i} = {Num*i}”)
59. Write a program to count the sum of digits in the entered number.
def is_palindrome(num):
num_str = str(num)
return num_str == num_str[::-1]
num = int(input("Enter a number: "))
if is_palindrome(num):
print(f"{num} is a palindrome.")
else:
print(f"{num} is not a palindrome.")
def is_armstrong(n):
n_str = str(n)
n_digits = len(n_str)
sum_powers = sum(int(d) ** n_digits for d in n_str)
return sum_powers == n
n = int(input("Enter a number: "))
if is_armstrong(n):
print(f"{n} is an Armstrong number.")
else:
print(f"{n} is not an Armstrong number.")
72. Write a program to find the Sum of all prime numbers from 1-1000.
sum = 0
for n in range(1, 1001):
c=1
for i in range(2, n):
if n % i == 0:
c=0
break
if c and n > 1:
sum += n
print(sum)
*****
*****
*****
*****
*****
for i in range(5):
for j in range(5):
print("*",end=" ")
print()
**
***
****
*****
for i in range(5):
for j in range(5):
print("*",end=" ")
print()
12
123
1234
12345
333
4444
55555
BB
CCC
DDDD
EEEEE
*****
****
***
**
1234
123
12
***
*****
*******
*********
n=5
for i in range(1, n + 1):
for j in range(n - i):
print(" ", end="")
for k in range(1, 2*i):
print("*", end="")
print()
34543
4567654
567898765
rows = 5
for i in range(1, rows + 1):
print(" " * (rows - i), end="")
for j in range(i, i * 2):
print(j, end="")
for j in range(i * 2 - 2, i - 1, -1):
print(j, end="")
print()
*********
*******
*****
***
rows = 5
for i in range(1, rows + 1):
print(" " * (rows - i), end="")
for j in range(i, i * 2):
print(j, end="")
for j in range(i * 2 - 2, i - 1, -1):
print(j, end="")
print()
1 1
1 2 1
1 3 3
1
1 4 46 1
1 5 10 10 5 1
def pascal_triangle(n):
for i in range(n):
row = [1] * (i + 1)
for j in range(1, i):
row[j] = row[j - 1] + row[j]
print(" " * (n - i - 1), end="")
print(" ".join(map(str, row)))
n=6
pascal_triangle(n)
23
456
7 8 9 10
num = 1
for i in range(1, 5):
for j in range(i):
print(num, end=" ")
num += 1
print()
BAB
ABABA
BABABAB
rows = 4
for i in range(1, rows + 1):
print(" " * (rows - i), end="")
for j in range(i):
if j % 2 == 0:
print("A", end=" ")
else:
print("B", end=" ")
print()
010
10101
0101010
rows = 4
for i in range(1, rows + 1):
print(" " * (rows - i), end="")
for j in range(i):
if (i + j) % 2 == 0:
print("1", end=" ")
else:
print("0", end=" ")
print()
AABCDEF FEDCB
AABCDE EDCBA
ABCD DCBA
ABC CBA
AB BA
A A
rows = 7
for i in range(rows):
for j in range(rows - i):
print(chr(65 + j), end=" ")
for k in range(i * 2 - 1):
print(" ", end=" ")
for l in range(rows - i - 1, -1, -1):
print(chr(65 + l), end=" ")
print()
**********
**** ****
*** ***
** **
* *
rows = 5
for i in range(rows):
for j in range(rows - i):
print("*", end="")
for k in range(i * 2 - 1):
print(" ", end="")
for l in range(rows - i):
print("*", end="")
print()
**
***
****
*****
*****
****
***
**
n=6
for i in range(1, n + 1):
print(" " * (n - i) + "* " * i)
for i in range(n - 1, 0, -1):
print(" " * (n - i) + "* " * i)
01
010
0101
01010
rows = 5
for i in range(1, rows + 1):
print(" " * (rows - i), end="")
for j in range(i):
if j % 2 == 0:
print("0", end=" ")
else:
print("1", end=" ")
print()
01 10
010 010
0101 1010
0101001010
rows = 5
for i in range(1, rows + 1):
print(" " * (rows - i), end="")
for j in range(i):
if j % 2 == 0:
print("0", end="")
else:
print("1", end="")
print(" " * (2 * (rows - i) - 1), end="")
for j in range(i):
if j % 2 == 0:
print("1", end="")
else:
print("0", end="")
print()
12 21
123 321
1234 4321
1234554321
rows = 5
for i in range(1, rows + 1):
for j in range(1, i + 1):
print(j, end="")
print(" " * (2 * (rows - i) - 1), end="")
for j in range(i, 0, -1):
print(j, end="")
print()
BC
DEF
GHIJ
KLMNO
rows = 5
char = 65
for i in range(1, rows + 1):
for j in range(i):
print(chr(char), end=" ")
char += 1
print()
A
BAB
CBABC
DCBABCD
EDCBABCDE
rows = 5
for i in range(1, rows + 1):
print(" " * (rows - i), end="")
for j in range(i):
print(chr(65 + i - j - 1), end="")
for j in range(i - 1):
print(chr(65 + j + 1), end="")
print()
1A2B3C4D5E
1A2B3C4D
1A2B3C
1A2B
1A
rows = 5
for i in range(rows, 0, -1):
for j in range(1, i + 1):
print(j, end="")
print(chr(64+j), end="")
print()
101
21012
3210123
432101234
rows = 5
for i in range(rows):
print(" " * (rows - i - 1), end="")
for j in range(i, -1, -1):
print(j, end=" ")
for j in range(1, i + 1):
print(j, end=" ")
print()
Functio
ns
101. Write a Python function to find the Max of three numbers.
def sum_of_list(numbers):
return sum(numbers)
lst = [1, 2, 3, 4, 5]
print(sum_of_list(lst))
def multiply_list(lst):
result = 1
for num in lst:
result *= num
return result
numbers = [8, 2, 3, -1, 7]
print("Product of all numbers:", multiply_list(numbers))
104. Write a Python program to reverse a string.
Sample String : "1234abcd"
Expected Output : "dcba4321"
107. Write a Python function that accepts a string and calculate the number of
upper-case letters and lower-case letters.
Sample String: 'The quick Brow Fox'
Expected Output :
No. of Upper case characters : 3
No. of Lower case Characters : 12
def count_case(s):
upper_case = sum(1 for c in s if c.isupper())
lower_case = sum(1 for c in s if c.islower())
print(f"No. of Upper case characters : {upper_case}")
print(f"No. of Lower case Characters : {lower_case}")
s = input("Enter a string: ")
count_case(s)
108. Write a Python function that takes a list and returns a new list
with unique elements of the first list.
Sample List : [1,2,3,3,3,3,4,5]
Unique List : [1, 2, 3, 4, 5]
def unique_elements(lst):
return list(set(lst))
lst = [1, 2, 2, 3, 4, 4, 5]
print("List with unique elements:", unique_elements(lst))
109. Write a Python function that takes a number as a parameter and check
the number is prime or not.
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
num = int(input("Enter a number: "))
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
def is_palindrome(s):
if s == s[::-1]:
return True
else:
return False
string = input("Enter String: ")
if is_palindrome(string):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
111. Write a Python function that prints out the first n rows of Pascal's
triangle.
def pascal_triangle(n):
for i in range(n):
row = [1] * (i + 1)
for j in range(1, i):
row[j] = row[j - 1] + row[j]
print(" ".join(map(str, row)).center(n * 2))
n = int(input("Enter number of rows : "))
pascal_triangle(n)
def is_pangram(s):
alphabet = set('abcdefghijklmnopqrstuvwxyz')
return set(s.lower()) >= alphabet
string = input("Enter a string: ")
if is_pangram(string):
print("The string is a pangram.")
else:
print("The string is not a pangram.")
113. Write a Python function that accepts a hyphen-separated sequence
of words as input and prints the words in a hyphen-separated sequence after
sorting them alphabetically.
Sample Items: green-red-yellow-black-white
Expected Result: black-green-red-white-yellow
def words(input_string):
words = input_string.split('-')
words.sort()
print('-'.join(words))
input_string = input("Enter a hyphen-separated sequence of words:
")
words(input_string)
114. Python function to convert height (in feet and inches) to centimeters.
def celsius_to_fahrenheit(celsius):
fahrenheit = (celsius * 9/5) + 32
return fahrenheit
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = celsius_to_fahrenheit(celsius)
print(f"Temperature in Fahrenheit: {fahrenheit:.2f}°F")
Recursion:
117. Write a program using recursion to compute factorial of a
given number.
def fact(n):
if n==0 or n==1:
return 1
else:
return n*fact(n-1)
num=int(input(“Enter a number to compute its factorial : ”))
if num<0:
print(“Factorial is not defined for negative number ”)
else:
result=fact(num)
print(f”The Factorial of {num} is: {result}”)
def fibo(n):
if n<= 0:
return 0
elif n== 1:
return 1
else:
return fibo(n-1) + fibo(n-2)
num_terms=int(input(“Enter the number of the terms in the
Fibonacci series : ”))
print(“Fibonacci Series: ”)
for I in range(num_terms):
print(fibo(i),end=” ”)
def sum_of_num(n):
if n == 1:
return 1
else:
return n+ sum_of_num(n-1)
N = int(input(“Enter a number N: ”))
Result = sum_of_num(N)
print(f”The sum of number from 1 to {N} is : {Result}”)
120. Write a program to Find Sum of Digits of the Number using Recursive
Function.
def sum_of_digits(n):
if n == 0:
return 0
else:
return n % 10 + sum_of_digits(n // 10)
n = int(input("Enter a number: "))
result = sum_of_digits(n)
print(f"Sum of digits of {n} is {result}")
122. Python Program to Determine How Many Times a Given Letter Occurs
in a String Recursively
def binary_equivalent(n):
if n == 0:
return ""
else:
return binary_equivalent(n // 2) + str(n % 2)
n = int(input("Enter a number: "))
binary = binary_equivalent(n)
if n == 0:
binary = "0"
print(f"The binary equivalent of {n} is {binary}")
124. Python Program to Find the GCD of Two Numbers Using Recursion.
def is_palindrome(s):
if len(s) <= 1:
return True
elif s[0] != s[-1]:
return False
else:
return is_palindrome(s[1:-1])
input_string = input("Enter a string: ")
if is_palindrome(input_string):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
def reverse_str(s):
if len(s) == 0:
return s
else:
return reverse_str(s[1:] + s[0])
string = input(“Enter a string : ”)
reversed_string=reverse_str(string)
print(f“The reversed string is :{reversed_string}”)
129. WAP to convert a list of string type numbers into list of integer
type numbers using map function.
130. WAP to find the largest element in the list using reduce function.
131. WAP to compute the cube of all numbers in the given list using
map() function.
133. WAP to create a new list consisting of odd numbers from the given
list of numbers using filter() function.
134. WAP to compute the sum of all the elements of the list using
reduce() function.
4. Create a class called Numbers, which has a single class attribute called
MULTIPLIER, and a constructor which takes the parameters x and y (these
should all be numbers).
a. Write an instance method called add which returns the sum of the attributes
x and y.
b. Write a class method called multiply, which takes a single number parameter
a and returns the product of a and MULTIPLIER.
c. Write a static method called subtract, which takes two number objects, b and
c, and returns b - c.
d. Write a method called value which returns a tuple containing the values of
x and y.
class Numbers:
MULTIPLIER = 10
def init (self, x, y):
self.x = x
self.y = y
def add(self):
return self.x + self.y
@classmethod
def multiply(cls, a):
return a * cls.MULTIPLIER
@staticmethod
def subtract(b, c):
return b - c
def value(self):
return (self.x, self.y)
num = Numbers(5, 3)
print("Sum of x and y:", num.add())
print("Multiplication of a and MULTIPLIER:", Numbers.multiply(7))
print("Subtraction of b and c:", Numbers.subtract(10, 3))
print("Tuple of x and y:", num.value())
5. Create a class named as Student to store the name and marks in three subjects.
Use List to store the marks.
a. Write an instance method called compute to compute total marks and
average marks of a student.
b. Write a method called display to display student information.
class Student:
def init (self, name, marks):
self.name = name
self.marks = marks
def compute(self):
total_marks = sum(self.marks)
average_marks = total_marks / len(self.marks)
return total_marks, average_marks
def display(self):
total_marks, average_marks = self.compute()
print(f"Student Name: {self.name}")
print(f"Marks: {self.marks}")
print(f"Total Marks: {total_marks}")
print(f"Average Marks: {average_marks:.2f}")
marks = [85, 90, 88]
student = Student("Preeti", marks)
student.display()
8. Create a class called String that stores a string and all its status details such as
number of uppercase letters, lowercase letters, vowels ,consonants and space in
instance variables.
a. Write methods named as count_uppercase, count_lowercase, count_vowels,
count_consonants and count_space to count corresponding values.
b. Write a method called display to print string along with all the values
computed by methods in (a).
class String:
def init (self, text):
self.text = text
self.uppercase = 0
self.lowercase = 0
self.vowels = 0
self.consonants = 0
self.spaces = 0
self.calculate()
def count_uppercase(self):
return self.uppercase
def count_lowercase(self):
return self.lowercase
def count_vowels(self):
return self.vowels
def count_consonants(self):
return self.consonants
def count_space(self):
return self.spaces
def calculate(self):
vowels_set = "aeiouAEIOU"
for char in self.text:
if char.isupper():
self.uppercase += 1
elif char.islower():
self.lowercase += 1
if char in vowels_set:
self.vowels += 1
elif char.isalpha():
self.consonants += 1
elif char == ' ':
self.spaces += 1
def display(self):
print(f"String: {self.text}")
print(f"Uppercase letters: {self.count_uppercase()}")
print(f"Lowercase letters: {self.count_lowercase()}")
print(f"Vowels: {self.count_vowels()}")
print(f"Consonants: {self.count_consonants()}")
print(f"Spaces: {self.count_space()}")
str_obj = String("Hello World! This is Python.")
str_obj.display()
9. Write a program that has a class called Fraction with attributes numerator and
denominator.
a. Write a method called getdata to enter the values of the attributes.
b. Write a method show to print the fraction in simplified form.
import math
class Fraction:
def init (self):
self.numerator = 0
self.denominator = 1
def getdata(self):
self.numerator = int(input("Enter the numerator: "))
self.denominator = int(input("Enter the denominator: "))
def simplify(self):
gcd = math.gcd(self.numerator, self.denominator)
self.numerator = self.numerator // gcd
self.denominator = self.denominator // gcd
def show(self):
self.simplify()
print(f"The simplified fraction is:
{self.numerator}/{self.denominator}")
fraction = Fraction()
fraction.getdata()
fraction.show()
10. Write a program that has a class Numbers with a list as an instance variable.
a. Write a method called insert_element that takes values from user.
b. Write a class method called find_max to find and print largest value in the
list.
class Numbers:
def init (self):
self.numbers_list = []
def insert_element(self):
n = int(input("How many numbers do you want to enter? "))
for i in range(n):
num = int(input(f"Enter number {i+1}: "))
self.numbers_list.append(num)
@classmethod
def find_max(cls, numbers_list):
if len(numbers_list) > 0:
max_value = max(numbers_list)
print(f"The largest value in the list is: {max_value}")
else:
print("The list is empty.")
numbers = Numbers()
numbers.insert_element()
Numbers.find_max(numbers.numbers_list)
11. Write a program that has a class Point with attributes x and y.
a. Write a method called midpoint that returns a midpoint of a line joining
two points.
b. Write a method called length that returns the length of a line joining two
points.
import math
class Point:
def init (self, x, y):
self.x = x
self.y = y
def midpoint(self, other):
mx = (self.x + other.x) / 2
my = (self.y + other.y) / 2
return (mx, my)
def length(self, other):
dist = math.sqrt((self.x - other.x)**2 + (self.y - other.y)**2)
return dist
p1 = Point(1, 2)
p2 = Point(4, 6)
mid = p1.midpoint(p2)
dist = p1.length(p2)
print(f"Midpoint: {mid}")
print(f"Length: {dist}")
12. Create a class called Complex. Write a menu driven program to read, display,
add and subtract two complex numbers by creating corresponding instance
methods.
class Complex:
def init (self, real=0, imag=0):
self.real = real
self.imag = imag
def display(self):
print(f"{self.real} + {self.imag}i")
def add(self, other):
real_sum = self.real + other.real
imag_sum = self.imag + other.imag
return Complex(real_sum, imag_sum)
def subtract(self, other):
real_diff = self.real - other.real
imag_diff = self.imag - other.imag
return Complex(real_diff, imag_diff)
def main():
while True:
print("\nMenu:")
print("1. Read Complex Numbers")
print("2. Display Complex Numbers")
print("3. Add Complex Numbers")
print("4. Subtract Complex Numbers")
print("5. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
real1 = float(input("Enter real part of first complex number: "))
imag1 = float(input("Enter imaginary part of first complex number:
"))
real2 = float(input("Enter real part of second complex number: "))
imag2 = float(input("Enter imaginary part of second complex
number: "))
c1 = Complex(real1, imag1)
c2 = Complex(real2, imag2)
elif choice == 2:
print("First Complex Number: ", end="")
c1.display()
print("Second Complex Number: ", end="")
c2.display()
elif choice == 3:
result = c1.add(c2)
print("Addition Result: ", end="")
result.display()
elif choice == 4:
result = c1.subtract(c2)
print("Subtraction Result: ", end="")
result.display()
elif choice == 5:
print("Exiting the program.")
break
else:
print("Invalid choice, please try again.")
if name == " main ":
main()
13. Write a Program to illustrate the use of str (), repr (), new , doc ,
dict , name and bases methods.
bases methods
class Animal:
doc = "This is a class representing an Animal."
def new (cls, name):
print(f"Creating a new instance of {cls. name } class")
instance = super(Animal, cls). new (cls)
return instance
def init (self, name):
self.name = name
def str (self):
return f"The animal's name is {self.name}."
def repr (self):
return f"Animal(name={self.name!r})"
class Dog(Animal):
doc = "This is a class representing a Dog, inheriting from Animal."
def init (self, name, breed):
super(). init (name)
self.breed = breed
def str (self):
return f"{self.name} is a {self.breed} dog."
def repr (self):
return f"Dog(name={self.name!r}, breed={self.breed!r})"
dog = Dog("Buddy", "Golden Retriever")
print(str(dog))
print(repr(dog))
print(Animal. doc )
print(Dog. doc )
print(Animal. dict )
print(Dog. dict )
print(f"The name of the class is: {Dog. name }")
print(f"The base classes of Dog are: {Dog. bases }")
cat = Animal("Whiskers")
14. Create a BankAccount class. Your class should support the following methods:
a. init (self, account_no)
b. deposit (self, account_no, amount)
c. withdraw (self, account_no, amount)
d. get_balance (self, account_no)
class BankAccount:
def init (self, account_no):
self.account_no = account_no
self.balance = 0
def deposit(self, amount):
if amount > 0:
self.balance += amount
print(f"Deposited: {amount}. Current balance: {self.balance}")
else:
print("Amount should be greater than zero.")
def withdraw(self, amount):
if amount > 0 and amount <= self.balance:
self.balance -= amount
print(f"Withdrew: {amount}. Current balance: {self.balance}")
elif amount > self.balance:
print("Insufficient balance.")
else:
print("Amount should be greater than zero.")
def get_balance(self):
return f"Current balance: {self.balance}"
account = BankAccount("12345")
account.deposit(500)
account.withdraw(200)
print(account.get_balance())
account.withdraw(400)
print(account.get_balance())
class SampleClass:
def init (self, name, age):
self.name = name
self.age = age
obj = SampleClass("John", 25)
print("Has 'name' attribute:", hasattr(obj, 'name'))
print("Has 'address' attribute:", hasattr(obj, 'address'))
print("Name:", getattr(obj, 'name'))
print("Age:", getattr(obj, 'age'))
print("Address (default value):", getattr(obj, 'address', 'Not Available'))
setattr(obj, 'address', '1234 Elm Street')
print("Address after setting:", getattr(obj, 'address'))
delattr(obj, 'address')
print("Address after deletion:", getattr(obj, 'address', 'Not Available'))
16. Write a program to create class Employee. Display the personal information and
salary details of 5 employees using single inheritance.
class PD:
def init (self, n, a, ad, p):
self.n = n
self.a = a
self.ad = ad
self.p = p
def disp_personal(self):
print(f"Name: {self.n}")
print(f"Age: {self.a}")
print(f"Address: {self.ad}")
print(f"Phone: {self.p}")
print("-" * 30)
class SD(PD):
def init (self, n, a, ad, p, bs, b, d):
super(). init (n, a, ad, p)
self.bs = bs
self.b = b
self.d = d
self.ts = self.calc_salary()
def calc_salary(self):
return self.bs + self.b - self.d
def disp_salary(self):
print(f"Basic Salary: {self.bs}")
print(f"Bonus: {self.b}")
print(f"Deductions: {self.d}")
print(f"Total Salary: {self.ts}")
print("-" * 30)
e1 = SD("Preeti", 30, "Noida", "123-456-7890", 50000, 5000, 2000)
e2 = SD("Ram", 28, "456 Oak St.", "234-567-8901", 55000, 6000, 2500)
e3 = SD("Sam", 35, "789 Pine St.", "345-678-9012", 60000, 7000, 3000)
e4 = SD("Lisa", 40, "321 Maple St.", "456-789-0123", 65000, 8000, 3500)
e5 = SD("Tom", 32, "654 Birch St.", "567-890-1234", 70000, 9000, 4000)
emps = [e1, e2, e3, e4, e5]
for e in emps:
e.disp_personal()
e.disp_salary()
17. WAP that extends the class Employee. Derive two classes Manager and Team
Leader from Employee class. Display all the details of the employee working
under a particular Manager and Team Leader.
class Employee:
def init (self, name, age, address, phone):
self.name = name
self.age = age
self.address = address
self.phone = phone
def display_details(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")
print(f"Address: {self.address}")
print(f"Phone: {self.phone}")
print("-" * 30)
class Manager(Employee):
def init (self, name, age, address, phone, department):
super(). init (name, age, address, phone)
self.department = department
self.team = []
def add_employee(self, employee):
self.team.append(employee)
def display_team(self):
print(f"Manager: {self.name} (Department: {self.department})")
print("Employees under Manager:")
for emp in self.team:
emp.display_details()
class TeamLeader(Employee):
def init (self, name, age, address, phone, team_name):
super(). init (name, age, address, phone)
self.team_name = team_name
self.team = []
def add_employee(self, employee):
self.team.append(employee)
def display_team(self):
print(f"Team Leader: {self.name} (Team: {self.team_name})")
print("Employees under Team Leader:")
for emp in self.team:
emp.display_details()
e1 = Employee("John", 30, "Delhi", "46778899999")
e2 = Employee("Jane", 28, "Mumbai.", "8905678901")
e3 = Employee("Sam", 35, "Noida.", "3456789012")
e4 = Employee("Lisa", 40, "Noida.", "4567890123")
e5 = Employee("Tom", 32, "Mumbai.", "5678901234")
manager1 = Manager("Alice", 45, "Delhi", "6789012345", "HR")
team_leader1 = TeamLeader("Bob", 38, "Lucknow", "7890123456",
"Development")
manager1.add_employee(e1)
manager1.add_employee(e2)
team_leader1.add_employee(e3)
team_leader1.add_employee(e4)
team_leader1.add_employee(e5)
manager1.display_team()
team_leader1.display_team()
18. Write a program that has a class Point. Define another class Location which has
two objects (Location and destination) of class Point. Also, define a function in
Location that prints the reflection on the y-axis.
class Point:
def init (self, x, y):
self.x = x
self.y = y
def display(self):
print(f"Point({self.x}, {self.y})")
class Location:
def init (self, x, y, dest_x, dest_y):
self.location = Point(x, y)
self.destination = Point(dest_x, dest_y)
def reflect_on_y_axis(self):
reflected_location = Point(-self.location.x, self.location.y)
reflected_destination = Point(-self.destination.x, self.destination.y)
print("Reflection on the Y-axis:")
print(f"Location: Point({reflected_location.x},
{reflected_location.y})")
print(f"Destination: Point({reflected_destination.x},
{reflected_destination.y})")
loc = Location(2, 3, 4, -5)
loc.reflect_on_y_axis()
19. WAP that create a class Student having attribute as name and age and Marks
class inheriting Students class with its own attributes marks1, marks2 and
marks3 as marks in 3 subjects. Also, define the class Result that inherits the
Marks class with its own attribute total. Every class has its own display() method
to display the corresponding details. Use init () and super() to implement the
above classes.
class Student:
def init (self, name, age):
self.name = name
self.age = age
def display(self):
print(f"Student Name: {self.name}")
print(f"Student Age: {self.age}")
print("-" * 30)
class Marks(Student):
def init (self, name, age, marks1, marks2, marks3):
super(). init (name, age)
self.marks1 = marks1
self.marks2 = marks2
self.marks3 = marks3
def display(self):
super().display()
print(f"Marks in Subject 1: {self.marks1}")
print(f"Marks in Subject 2: {self.marks2}")
print(f"Marks in Subject 3: {self.marks3}")
print("-" * 30)
class Result(Marks):
def init (self, name, age, marks1, marks2, marks3):
super(). init (name, age, marks1, marks2, marks3)
self.total = self.calculate_total()
def calculate_total(self):
return self.marks1 + self.marks2 + self.marks3
def display(self):
super().display()
print(f"Total Marks: {self.total}")
print("-" * 30)
student1 = Result("Sam", 18, 85, 90, 95)
student2 = Result("Ram", 19, 78, 82, 88)
student1.display()
student2.display()
20. Write a program that create a class Distance with members km and metres.
Derive classes School and office which store the distance from your house to
school and office along with other details.
class Distance:
def init (self, km, metres):
self.km = km
self.metres = metres
def display(self):
print(f"Distance: {self.km} km {self.metres} metres")
class School(Distance):
def init (self, km, metres, name, grade):
super(). init (km, metres)
self.name = name
self.grade = grade
def display(self):
print(f"School Name: {self.name}")
print(f"Grade: {self.grade}")
super().display()
class Office(Distance):
def init (self, km, metres, company_name, position):
super(). init (km, metres)
self.company_name = company_name
self.position = position
def display(self):
print(f"Company Name: {self.company_name}")
print(f"Position: {self.position}")
super().display()
school = School(3, 500, "Sunshine High School", "12th Grade")
office = Office(5, 300, "Tech Solutions", "Software Developer")
print("School Details:")
school.display()
print("\nOffice Details:")
office.display()
21. Write a program to create an abstract class Vehicle. Derive three classes Car,
Motorcycle and Truck from it. Define appropriate methods and print the details
of vehicle.
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def display_details(self):
pass
class Car(Vehicle):
def init (self, make, model, year, color):
self.make = make
self.model = model
self.year = year
self.color = color
def display_details(self):
print(f"Car Details: \nMake: {self.make}\nModel:
{self.model}\nYear: {self.year}\nColor: {self.color}\n")
class Motorcycle(Vehicle):
def init (self, make, model, year, engine_capacity):
self.make = make
self.model = model
self.year = year
self.engine_capacity = engine_capacity
def display_details(self):
print(f"Motorcycle Details: \nMake: {self.make}\nModel:
{self.model}\nYear: {self.year}\nEngine Capacity:
{self.engine_capacity}cc\n")
class Truck(Vehicle):
def init (self, make, model, year, load_capacity):
self.make = make
self.model = model
self.year = year
self.load_capacity = load_capacity
def display_details(self):
print(f"Truck Details: \nMake: {self.make}\nModel:
{self.model}\nYear: {self.year}\nLoad Capacity: {self.load_capacity}
tons\n")
car = Car("Toyota", "Corolla", 2020, "Blue")
motorcycle = Motorcycle("Yamaha", "MT-07", 2022, 689)
truck = Truck("Volvo", "FH16", 2019, 18)
car.display_details()
motorcycle.display_details()
truck.display_details()
22. Write a program that has a class Polygon. Derive two classes Rectangle and
triangle from polygon and write methods to get the details of their dimensions
and hence calculate the area.
class Polygon:
def init (self):
pass
def area(self):
pass
class Rectangle(Polygon):
def init (self, length, width):
self.length = length
self.width = width
def get_details(self):
self.length = float(input("Enter the length of the rectangle: "))
self.width = float(input("Enter the width of the rectangle: "))
def area(self):
return self.length * self.width
class Triangle(Polygon):
def init (self, base, height):
self.base = base
self.height = height
def get_details(self):
self.base = float(input("Enter the base of the triangle: "))
self.height = float(input("Enter the height of the triangle: "))
def area(self):
return 0.5 * self.base * self.height
rect = Rectangle(0, 0)
tri = Triangle(0, 0)
rect.get_details()
print(f"Area of Rectangle: {rect.area()}")
tri.get_details()
print(f"Area of Triangle: {tri.area()}")
23. Write a program that extends the class Shape to calculate the area of a circle and
a cone .(use super to inherit base class methods)
import math
class Shape:
def init (self):
pass
def area(self):
pass
class Circle(Shape):
def init (self, radius):
super(). init ()
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
class Cone(Shape):
def init (self, radius, height):
super(). init ()
self.radius = radius
self.height = height
def area(self):
slant_height = math.sqrt(self.radius ** 2 + self.height ** 2)
return math.pi * self.radius * (self.radius + slant_height)
circle = Circle(5)
cone = Cone(5, 12)
print(f"Area of Circle: {circle.area():.2f}")
print(f"Surface Area of Cone: {cone.area():.2f}")
24. Write a program to demonstrate hybrid inheritance and show MRO for each
class.
class A:
def init (self):
print("Class A Constructor")
def method(self):
print("Class A Method")
class B(A):
def init (self):
super(). init ()
print("Class B Constructor")
def method(self):
super().method()
print("Class B Method")
class C(A):
def init (self):
super(). init ()
print("Class C Constructor")
def method(self):
super().method()
print("Class C Method")
class D(B, C):
def init (self):
super(). init ()
print("Class D Constructor")
def method(self):
super().method()
print("Class D Method")
d = D()
print("\nMRO for class D:", D.mro())
25. Write a program to overload + operator to multiply to fraction object of
fraction class which contain two instance variable numerator and
denominator. Also, define the instance method simplify() to simplify the
fraction objects.
import math
class Fraction:
def init (self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
self.simplify()
def simplify(self):
gcd = math.gcd(self.numerator, self.denominator)
self.numerator //= gcd
self.denominator //= gcd
def add (self, other):
new_numerator = self.numerator * other.numerator
new_denominator = self.denominator * other.denominator
result = Fraction(new_numerator, new_denominator)
return result
def str (self):
return f"{self.numerator}/{self.denominator}"
frac1 = Fraction(3, 4)
frac2 = Fraction(2, 5)
result = frac1 + frac2
print("Result of multiplying the fractions:", result)
28. WAP to create a Complex class having real and imaginary as it attributes.
Overload the +,-,/,* and += operators for objects of Complex class.
class Complex:
def init (self, real, imaginary):
self.real = real
self.imaginary = imaginary
def add (self, other):
return Complex(self.real + other.real, self.imaginary
+ other.imaginary)
def sub (self, other):
return Complex(self.real - other.real, self.imaginary -
other.imaginary)
def mul (self, other):
real_part = self.real * other.real - self.imaginary * other.imaginary
imaginary_part = self.real * other.imaginary + self.imaginary
* other.real
return Complex(real_part, imaginary_part)
def truediv (self, other):
denominator = other.real**2 + other.imaginary**2
real_part = (self.real * other.real + self.imaginary * other.imaginary)
/ denominator
imaginary_part = (self.imaginary * other.real - self.real *
other.imaginary) / denominator
return Complex(real_part, imaginary_part)
def iadd (self, other):
self.real += other.real
self.imaginary += other.imaginary
return self
def str (self):
return f"{self.real} + {self.imaginary}i"
c1 = Complex(3, 2)
c2 = Complex(1, 7)
print(f"c1: {c1}")
print(f"c2: {c2}")
c3 = c1 + c2
print(f"c1 + c2 = {c3}")
c4 = c1 - c2
print(f"c1 - c2 = {c4}")
c5 = c1 * c2
print(f"c1 * c2 = {c5}")
29. Write a program to inspect the object using type() ,id(), isinstance(), issubclass()
and callable() built-in function.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
def greet():
print("Hello, world!")
animal = Animal()
dog = Dog()
greeting_func = greet
print("Type of animal:", type(animal))
print("Type of dog:", type(dog))
print("Type of greeting_func:", type(greeting_func))
print("ID of animal:", id(animal))
print("ID of dog:", id(dog))
print("Is animal an instance of Animal?", isinstance(animal, Animal))
print("Is dog an instance of Dog?", isinstance(dog, Dog))
print("Is dog an instance of Animal?", isinstance(dog, Animal))
print("Is Dog a subclass of Animal?", issubclass(Dog, Animal))
print("Is Animal a subclass of Dog?", issubclass(Animal, Dog))
print("Is greet callable?", callable(greeting_func))
print("Is animal callable?", callable(animal))
print("Is dog callable?", callable(dog))
30. WAP to inspect the program code using the functions of inspect module.
import inspect
class MyClass:
def my_method(self, x, y):
return x + y
def my_function(a, b):
return a * b
print("Inspecting MyClass:")
print(inspect.getmembers(MyClass))
print("\nInspecting method 'my_method':")
print(inspect.getmembers(MyClass, predicate=inspect.isfunction))
print("\nInspecting function 'my_function':")
print(inspect.getsource(my_function))
print("\nInspecting arguments of 'my_function':")
print(inspect.signature(my_function))
print("\nInspecting the file where 'my_function' is defined:")
print(inspect.getfile(my_function))
print("\nChecking if 'my_function' is a function:",
inspect.isfunction(my_function))
print("Checking if 'my_function' is a module:",
inspect.ismodule(my_function))
31. Write a program to create a new list containing the first letters of every element
in an already existing list.
existing_list = ["apple", "banana", "cherry", "date", "elderberry"]
first_letters = [item[0] for item in existing_list]
print(first_letters)
32. Write a program using reduce() function to calculate the sum of first 10 natural
numbers
from functools import reduce
numbers = list(range(1, 11))
sum_of_numbers = reduce(lambda x, y: x + y, numbers)
print(sum_of_numbers)
33. Write a program that convert a list of temperatures in Celsius into Fahrenheit
using map() function.
celsius_temperatures = [0, 10, 20, 30, 40, 50]
fahrenheit_temperatures = list(map(lambda c: (c * 9/5) + 32,
celsius_temperatures))
print(fahrenheit_temperatures)
35. Write a program that create a custom iterator to create even numbers.
class EvenNumberIterator:
def init (self, start, end):
self.start = start if start % 2 == 0 else start + 1
self.end = end
def iter (self):
return self
def next (self):
if self.start > self.end:
raise StopIteration
else:
current = self.start
self.start += 2
return current
iterator = EvenNumberIterator(1, 10)
for even_number in iterator:
print(even_number)
36. Write a program to create a generator that starts counting from 0 and raise an
exception when counter is equal to 10.
def counting_generator():
counter = 0
while True:
if counter == 10:
raise Exception("Counter reached 10")
yield counter
counter += 1
gen = counting_generator()
try:
for number in gen:
print(number)
except Exception as e:
print(e)
39. Write a program to draw colored shapes (line, rectangle, oval) on canvas.
import tkinter as tk
def draw_shapes():
canvas.create_line(50, 50, 250, 50, fill="blue", width=5)
canvas.create_rectangle(50, 100, 250, 200, outline="green", width=3,
fill="yellow")
canvas.create_oval(50, 250, 250, 350, outline="red", width=3,
fill="pink")
root = tk.Tk()
root.title("Draw Colored Shapes")
canvas = tk.Canvas(root, width=300, height=400)
canvas.pack()
draw_shapes()
root.mainloop()
41. Write a program to create a button and a label inside the frame widget. Button
should change the color upon hovering over the button and label should
disappear on clicking the button.
import tkinter as tk
def on_button_hover(event):
button.config(bg="yellow")
def on_button_leave(event):
button.config(bg="lightgray")
def on_button_click():
label.pack_forget()
root = tk.Tk()
root.title("Button and Label Inside Frame")
frame = tk.Frame(root)
frame.pack(padx=20, pady=20)
label = tk.Label(frame, text="This is a label", font=("Arial", 14))
label.pack()
button = tk.Button(frame, text="Click Me", font=("Arial", 14),
bg="lightgray", command=on_button_click)
button.pack(pady=10)
button.bind("<Enter>", on_button_hover)
button.bind("<Leave>", on_button_leave)
root.mainloop()
42. Write a program to create radio-buttons (Male, Female, and Transgender) and a
label. Default selection should be on Female and the label must display the
current selection made by user.
import tkinter as tk
def display_selection():
selected = gender_var.get()
label.config(text=f"Selected: {selected}")
root = tk.Tk()
root.title("Radio Button Selection")
gender_var = tk.StringVar()
gender_var.set("Female")
frame = tk.Frame(root)
frame.pack(padx=20, pady=20)
label = tk.Label(frame, text="Selected: Female", font=("Arial", 14))
label.pack()
male_rb = tk.Radiobutton(frame, text="Male", variable=gender_var,
value="Male", font=("Arial", 12), command=display_selection)
male_rb.pack(anchor="w")
female_rb = tk.Radiobutton(frame, text="Female", variable=gender_var,
value="Female", font=("Arial", 12), command=display_selection)
female_rb.pack(anchor="w")
transgender_rb = tk.Radiobutton(frame, text="Transgender",
variable=gender_var, value="Transgender", font=("Arial", 12),
command=display_selection)
transgender_rb.pack(anchor="w")
root.mainloop()
44. Write a NumPy program to create an array of (3, 4) shape, multiply every
element value by 3 and display the new array.
import numpy as np
arr = np.random.randint(1, 10, size=(3, 4))
new_arr = arr * 3
print("Original Array:")
print(arr)
print("\nNew Array (multiplied by 3):")
print(new_arr)
45. Write a NumPy program to compute the multiplication of two given matrixes.
import numpy as np
matrix1 = np.array([[1, 2], [3, 4], [5, 6]])
matrix2 = np.array([[7, 8], [9, 10]])
result = np.matmul(matrix1, matrix2)
print(matrix1)
print("\n", matrix2)
print("\n", result)
46. Write a Program to create a series from a list, numpy array and dict.
import pandas as pd
import numpy as np
list_data = [10, 20, 30, 40]
series_from_list = pd.Series(list_data)
print("Series from List:")
print(series_from_list)
numpy_array = np.array([1, 2, 3, 4, 5])
series_from_numpy = pd.Series(numpy_array)
print("\nSeries from NumPy Array:")
print(series_from_numpy)
dict_data = {'a': 1, 'b': 2, 'c': 3}
series_from_dict = pd.Series(dict_data)
print("\nSeries from Dictionary:")
print(series_from_dict)
50. Write a Pandas program to create a line plot of the opening, closing stock
prices of Alphabet Inc. between two specific dates. Use the
alphabet_stock_data.csv file to extract data.
class Person:
def init (self, name, age):
self.name = name
self.age = age
def display_info(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")
person1 = Person("Ram", 25)
print(f"Name: {person1.name}")
print(f"Age: {person1.age}")
person1.display_info()