0% found this document useful (0 votes)
5 views

harshitsinghpython.py

The document contains a list of Python programming exercises and their solutions, covering various topics such as basic arithmetic operations, area and volume calculations, and data input/output. Each program is presented with a brief description and the corresponding code snippet. The exercises are designed to help learners practice problem-solving skills using Python.

Uploaded by

harshitnhs3225
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

harshitsinghpython.py

The document contains a list of Python programming exercises and their solutions, covering various topics such as basic arithmetic operations, area and volume calculations, and data input/output. Each program is presented with a brief description and the corresponding code snippet. The exercises are designed to help learners practice problem-solving skills using Python.

Uploaded by

harshitnhs3225
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 82

Name: Harshit singh

Course: MCA – ‘A’

ERP ID: 0241MCA186

List of Programs Problem Solving Using Python


(Solutions)

1. Python Program to Print Hello World!

 print("Hello World!")

2. Write a program for the addition of Two Numbers.

 a = float(input("Enter first number: "))

 b = float(input("Enter second number: "))

 print("The sum is:", a + b)

3. Write a program to Read Two Numbers and Print Their Quotient


and Remainder.

 a = int(input("Enter the dividend: "))

 b = int(input("Enter the divisor: "))

 quotient = a // b

 remainder = a % b

 print("Quotient:", quotient)

 print("Remainder:", remainder)

4. Write a program to Find the Average of Three Numbers.

 a = float(input("Enter first number: "))

 b = float(input("Enter second number: "))

 c = float(input("Enter third number: "))

 average = (a + b + c) / 3

 print("The average is:", average)


5. Write a program to Calculate Sum of 5 Subjects and Find
Percentage (Max Mark in each subject is 100).

 marks = []

 for i in range(5):

 marks.append(float(input(f"Enter marks for subject {i + 1}:


")))

 total = sum(marks)

 percentage = (total / 500) * 100

 print("Total Marks:", total)

 print("Percentage:", percentage)

6. Write a program to find gross salary.

 basic_salary = float(input("Enter the basic salary: "))

 hra = float(input("Enter HRA: "))

 da = float(input("Enter DA: "))

 gross_salary = basic_salary + hra + da

 print("Gross Salary:", gross_salary)

7. Write a program to Calculate Area of Rectangle, Square.

 length = float(input("Enter the length of the rectangle: "))

 breadth = float(input("Enter the breadth of the rectangle: "))

 side = float(input("Enter the side of the square: "))

 rectangle_area = length * breadth

 square_area = side ** 2

 print("Area of Rectangle:", rectangle_area)

 print("Area of Square:", square_area)


8. Write a program to Calculate Area of Scalene Triangle and Right-
angle Triangle.

 # For Scalene Triangle

 a = float(input("Enter side a: "))

 b = float(input("Enter side b: "))

 c = float(input("Enter side c: "))

 s = (a + b + c) / 2 # Semi-perimeter

 scalene_area = (s * (s - a) * (s - b) * (s - c)) ** 0.5

 print("Area of Scalene Triangle:", scalene_area)

 # For Right-angle Triangle

 base = float(input("Enter the base of the right triangle: "))

 height = float(input("Enter the height of the right triangle: "))

 right_triangle_area = 0.5 * base * height

 print("Area of Right-angle Triangle:", right_triangle_area)

9. Write a program to find the volume and surface area of cube,


cuboids and cylinder.

 # Cube

 side = float(input("Enter the side of the cube: "))

 cube_volume = side ** 3

 cube_surface_area = 6 * (side ** 2)

 print("Cube Volume:", cube_volume)

 print("Cube Surface Area:", cube_surface_area)

 # Cuboid

 length = float(input("Enter the length of the cuboid: "))

 breadth = float(input("Enter the breadth of the cuboid: "))

 height = float(input("Enter the height of the cuboid: "))

 cuboid_volume = length * breadth * height


 cuboid_surface_area = 2 * (length * breadth + breadth *
height + height * length)

 print("Cuboid Volume:", cuboid_volume)

 print("Cuboid Surface Area:", cuboid_surface_area)

 # Cylinder

 radius = float(input("Enter the radius of the cylinder: "))

 height = float(input("Enter the height of the cylinder: "))

 cylinder_volume = 3.1416 * radius ** 2 * height

 cylinder_surface_area = 2 * 3.1416 * radius * (radius + height)

 print("Cylinder Volume:", cylinder_volume)

 print("Cylinder Surface Area:", cylinder_surface_area)

10. Write a program to Calculate Volume and surface area of


Cone, Sphere and Cylinder.

 # Cone

 radius = float(input("Enter the radius of the cone: "))

 height = float(input("Enter the height of the cone: "))

 slant_height = (radius ** 2 + height ** 2) ** 0.5

 cone_volume = (1 / 3) * 3.1416 * radius ** 2 * height

 cone_surface_area = 3.1416 * radius * (radius + slant_height)

 print("Cone Volume:", cone_volume)

 print("Cone Surface Area:", cone_surface_area)

 # Sphere

 radius = float(input("Enter the radius of the sphere: "))

 sphere_volume = (4 / 3) * 3.1416 * radius ** 3

 sphere_surface_area = 4 * 3.1416 * radius ** 2

 print("Sphere Volume:", sphere_volume)

 print("Sphere Surface Area:", sphere_surface_area)


 # Cylinder (reuse values if needed)

 radius = float(input("Enter the radius of the cylinder: "))

 height = float(input("Enter the height of the cylinder: "))

 cylinder_volume = 3.1416 * radius ** 2 * height

 cylinder_surface_area = 2 * 3.1416 * radius * (radius + height)

 print("Cylinder Volume:", cylinder_volume)

 print("Cylinder Surface Area:", cylinder_surface_area)

11. Write a program to find the area of trapezium, rhombus and


parallelogram.

 # Trapezium

 a = float(input("Enter the length of first parallel side of


trapezium: "))

 b = float(input("Enter the length of second parallel side of


trapezium: "))

 h = float(input("Enter the height of the trapezium: "))

 trapezium_area = 0.5 * (a + b) * h

 print("Area of Trapezium:", trapezium_area)

 # Rhombus

 d1 = float(input("Enter the length of first diagonal of rhombus:


"))

 d2 = float(input("Enter the length of second diagonal of


rhombus: "))

 rhombus_area = 0.5 * d1 * d2

 print("Area of Rhombus:", rhombus_area)

 # Parallelogram

 base = float(input("Enter the base of the parallelogram: "))

 height = float(input("Enter the height of the parallelogram: "))


 parallelogram_area = base * height

 print("Area of Parallelogram:", parallelogram_area)

12. Write a program to find the perimeter of a circle, rectangle


and triangle.

 # Circle

 radius = float(input("Enter the radius of the circle: "))

 circle_perimeter = 2 * 3.1416 * radius

 print("Perimeter of Circle:", circle_perimeter)

 # Rectangle

 length = float(input("Enter the length of the rectangle: "))

 breadth = float(input("Enter the breadth of the rectangle: "))

 rectangle_perimeter = 2 * (length + breadth)

 print("Perimeter of Rectangle:", rectangle_perimeter)

 # Triangle

 a = float(input("Enter side a of the triangle: "))

 b = float(input("Enter side b of the triangle: "))

 c = float(input("Enter side c of the triangle: "))

 triangle_perimeter = a + b + c

 print("Perimeter of Triangle:", triangle_perimeter)

13. Write a program to Compute Simple Interest.

 P = float(input("Enter the principal amount: "))

 R = float(input("Enter the rate of interest: "))

 T = float(input("Enter the time in years: "))

 simple_interest = (P * R * T) / 100

 print("Simple Interest:", simple_interest)


14. Write a program to Convert Fahrenheit temperature in to
Celsius.

 F = float(input("Enter temperature in Fahrenheit: "))

 C = (F - 32) * 5 / 9

 print("Temperature in Celsius:", C)

15. Write a program to Find the Gravitational Force Acting


Between Two Objects.

 G = 6.674 * 10**-11 # Gravitational constant

 m1 = float(input("Enter mass of the first object (kg): "))

 m2 = float(input("Enter mass of the second object (kg): "))

 r = float(input("Enter distance between the objects (m): "))

 force = G * (m1 * m2) / r**2

 print("Gravitational Force:", force, "N")

16. Write a program to swap the values of two variables with and
without using third variable.

 # Using a third variable

 a = float(input("Enter the value of a: "))

 b = float(input("Enter the value of b: "))

 temp = a

 a=b

 b = temp

 print("After swapping (with third variable): a =", a, "b =", b)

 # Without using a third variable

 a=a+b

 b=a-b

 a=a-b
 print("After swapping (without third variable): a =", a, "b =",
b)

17. Write a program to perform arithmetic operations on a = 8, b


= 3.

 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)

18. Write a program to apply relational operations on a=8, b=3.

 a=8

 b=3

 print("a > b:", a > b)

 print("a < b:", a < b)

 print("a == b:", a == b)

 print("a != b:", a != b)

 print("a >= b:", a >= b)

 print("a <= b:", a <= b)

19. Write a program to apply assignment operations on a=8, b=3.

 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

 print("After a //= b:", a)

 a %= b

 print("After a %= b:", a)

 a **= b

 print("After a **= b:", a)

20. Write a program to apply logical operations on a=8, b=3.

 a=8

 b=3

 print("a > b and b > 0:", a > b and b > 0)

 print("a < b or b > 0:", a < b or b > 0)

 print("not (a > b):", not (a > b))

21. Write a program to apply bitwise operations on 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
22. Write a program to apply identity operators.

 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

 a=int(input(“Enter the value of a : ”))


 b=int(input(“Enter the value of b : ”))
 a=a^b
 b=a^b
 a=a^b
 print(f”After Swapping : a= {a},b= {b}”)

24. Write a program to multiply given Number by 4 using Bitwise


Operators.

 Num =int(input(“Enter a number: ”))


 Result=Num<<2
 print(f”{Num} multiplied by 4 is {Result}”)

25. Python Program to Find the Square Root.

 import math
 n=int(input(“Enter the Number :”))
 print(“Square of the number”,n,”is”,n**2)

26. Python program to convert all units of time into seconds.

 hours=int(input(“Enter hours :”))


 minutes=int(input(“Enter minutes :”))
 seconds=int(input(“Enter seconds :”))
 total=hours*3600+minutes*60+seconds
 print(f“The total time in seconds is : {total}”)
27. Python program to calculate midpoints of a line-segment.

 X1=float(input(“Enter the x-coordinate of 1st :”))


 Y1=float(input(“Enter the y-coordinate of 1st:”))
 X2=float(input(“Enter the x-coordinate of 2nd:”))
 Y2=float(input(“Enter the y-coordinate of 2nd:”))
 midpoint_x=(x1+x2)/2
 midpoint_y=(y1+y2)/2
 print(f“The midpoint of the line segment is: {midpoint_x},
{midpoint_y}”)

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 1 st
point”).split())
 x2,y2=map(float,input(“Enter the coordinates of the 2 nd
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}”)

30. WAP to find the absolute value of the given number.

 Num=float(input(“Enter a number: ”))


 Absolute_value=abs(Num)
 print(f”The absolute value of {Num} is: {Absolute}”)

31. WAP to demonstrate implicit and explicit type conversion.

 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)})”)

32. WAP to compute -9+9-8*6%8-int (19//10/2) |12&14 also


explain operator precedence.

 result= -9+9-8*6%8-int(19/10/2)|12&14
 print(f”The Result of the expression is: {result}”)

33. WAP to reverse a string.

 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.

 num1=float(input(“”Enter the 1st number: “))


 num2=float(input(“”Enter the 2nd number: “))
 if num1 == num2:
 print(“Numbers are equal”)
 else:
 print(“Numbers are not equal”)

36. Write a program to Check if a given Integer is Positive or


Negative and odd or Even.

 num = int(input(“Enter an integer: ”))


 if num>0:
 print(“Numbers is Positive”)
 elif num<0:
 print(“Numbers is negative”)
 else:
 print(“Numbers is Zero”)
 if num%2==0:
 print(“Numbers is Even”)
 else:
 print(“Numbers is Odd”)

37. Write a program to Check if a given Integer is Divisible by 7 or


not.

 num = int(input(“Enter an integer: ”))


 if num%7==0:
 print(“Numbers is divisible by 7”)
 else:
 print(“Numbers is not divisible by 7”)

38. Write a program to find the greatest of three numbers using


else if ladder.

 Num1 = int(input(“Enter an 1st number: ”))


 Num2 = int(input(“Enter an 2nd number: ”))
 Num3 = int(input(“Enter an 3rd number: ”))
 if Num1>= Num2 and Num1>=Num3:
 print(f“{Num1}is greatest”)
 elif Num2>= Num1 and Num2>=Num3:
 print(f“{Num2}is greatest”)
 else:
 print(f“{Num3}is greatest”)
39. Write a program to find the greatest of three numbers using
Nested if.

 Num1 = int(input(“Enter an 1st number: ”))


 Num2 = int(input(“Enter an 2nd number: ”))
 Num3 = int(input(“Enter an 3rd number: ”))
 if Num1>=Num2:
 if Num1>=Num3:
 greatest=Num1
 else:
 greatest=Num3
 else:
 if Num2>=Num3:
 greatest=Num2
 else:
 greatest=Num3
 print(f”The greatest number is: {greatest}”)

40. Write a program to convert an Upper-case character into lower


case and vice-versa.

 char= input(“Enter a character: ”)


 asci_value=ord(char)
 if ‘A’<= char <= ‘Z’:
 print(asci_value+32)
 elif ‘a’<= char <=’z’:
 print(asci_value-32)
 else:
 print(char)

41. Write a program to check weather an entered year is leap year


or not.

 Year=int(input(“Enter a year: ”))


 if(year % 4 ==0 and year % 100 !=)or(year % 400 ==0):
 print(f”{year} is a leap year.”)
 else
 print(f”{year} is not a leap year.”)

42. Write a Program to check whether an alphabet entered by the


user is a vowel or a constant.

 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”)

43. Write a program to Read a Coordinate Point and determine its


Quadrant.

 x = float(input(“Enter the X-coordinate: ”))


 y = float(input(“Enter the Y-coordinate: ”))
 if x>0 and y>0:
 print(“The point is in Quadrant 1.”)
 if x<0 and y>0:
 print(“The point is in Quadrant 2.”)
 if x<0 and y<0:
 print(“The point is in Quadrant 3.”)
 if x>0 and y<0:
 print(“The point is in Quadrant 4.”)
 if x == 0 and y> == 0:
 print(“The point is in the origin.”)
 elif x == 0:
 print(“The point lies on the y-axis.”)
 else:
 print(“The point lies on the x-axis.”)

44. Write a program to add two Complex Numbers.

 real1=float(input(“Enter the real part of 1st number: ”))


 imag1=float(input(“Enter the imaginary part of 1st number:
”))
 real2=float(input(“Enter the real part of 2nd number: ”))
 imag2=float(input(“Enter the imaginary part of 2nd number:
”))
 real=real1+real2
 imag=imag1+imag2
 print(f”The sum of the two complex number is : {real} +
{imag}”)

45. Write a Program to find roots of a quadratic expression.

 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.

 day=int(input(“Enter the day number: ”))


 if day == 1:
 print(“Monday”)
 if day == 2:
 print(“Tuesday”)
 if day == 3:
 print(“Wednesday”)
 if day == 4:
 print(“Thrusday”)
 if day == 5:
 print(“Friday”)
 if day == 6:
 print(“Saturday”)
 if day == 7:
 print(“Sunday”)
 else:
 print(“Invalid day number! ”)

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.”)

48. Write a program to Simulate Arithmetic Calculator.

 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.

 print("Select the shape to calculate the area:")


 print("1. Circle")
 print("2. Square")
 print("3. Rectangle")
 print("4. Triangle")

 choice = input("Enter choice (1/2/3/4): ")

 if choice == '1':
 radius = float(input("Enter radius of the circle: "))
 area = 3.14159 * radius * radius
 print(f"The area of the circle is: {area}")
 elif choice == '2':
 side = float(input("Enter side of the square: "))
 area = side * side
 print(f"The area of the square is: {area}")
 elif choice == '3':
 length = float(input("Enter length of the rectangle: "))
 width = float(input("Enter width of the rectangle: "))
 area = length * width
 print(f"The area of the rectangle is: {area}")
 elif choice == '4':
 base = float(input("Enter base of the triangle: "))
 height = float(input("Enter height of the triangle: "))
 area = 0.5 * base * height
 print(f"The area of the triangle is: {area}")
 else:
 print("Invalid input!")

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’.
 marks1 = float(input("Enter marks for subject 1: "))
 marks2 = float(input("Enter marks for subject 2: "))
 marks3 = float(input("Enter marks for subject 3: "))
 marks4 = float(input("Enter marks for subject 4: "))
 marks5 = float(input("Enter marks for subject 5: "))

 total_marks = marks1 + marks2 + marks3 + marks4 +
marks5
 percentage = (total_marks / 500) * 100

 print(f"Percentage: {percentage}%")
 if percentage >= 90:
 print("Grade: A")
 elif percentage >= 80:
 print("Grade: B")
 elif percentage >= 60:
 print("Grade: C")
 elif percentage >= 50:
 print("Grade: D")
 elif percentage >= 40:
 print("Grade: E")
 else:
 print("Grade: F")

51. WAP to enter a character and then determine whether it is a


vowel, consonants, or a digit.

 char = input("Enter a character: ")



 if char.isdigit():
 print(f"{char} is a digit")
 elif char in 'aeiouAEIOU':
 print(f"{char} is a vowel")
 else:
 print(f"{char} is a consonant")

LOOPS:

52. Write a program to display all even numbers from 1 to 20

 for num in range(1,21):


 if num%2==0:
 print(num)
53. Write a program to print all the Numbers Divisible by 7 from 1
to 100.

 for num in range(1,101):


 if num%7==0:
 print(num)

54. Write a program to print table of any number.

 Num=int(input(“Enter a number: ”))


 print(f”Multiplication table of {Num}:”)
 for I in range(1,11):
 print(f”{Num} X {i} = {Num*i}”)

55. Write a program to print 1, 2,3,5,6,7,8,9 use continue


statement.

 for num in range(1,10):


 if num==4:
 continue
 print(num)

56. Write a program to print table of 5 in following format.

5X1=5

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}”)

57. Write a program to find the Sum of first 50 Natural Numbers


using for Loop.

 for num in range(1,51):


 sum_of_no +=num
 print(f”The sum of the first 50 natural numbers is :
{sum_of_no}”)
58. Write a program to calculate factorial of a given number using
for loop and also using while loop.

 #using While loop


 Num = int(input(“Enter a number : ”))
 Fact_while=1
 i=1
 while i<=Num:
 Fact_while *=i
 i+=1
 print(“Factorial of {Num} is : {Fact_while}”)
 #using for loop
 Num = int(input(“Enter a number : ”))
 Fact_for=1
 For I in range(1,num+1):
 Fact_for *= i
 print(“Factorial of {Num} is : {Fact_for}”)

59. Write a program to count the sum of digits in the entered


number.

 Num=int(input(“Enter a number: ”))


 sum_of_digit =0
 while Num>0:
 digit = Num%10
 sum_of_digit +=digit
 Num //=10
 print(f”The Sum of the digits is: {sum_of_digit}”)

60. Write a program to find the reverse of a given number.

 number = int(input("Enter a number: "))


 reverse = 0

 while number > 0:
 reverse = reverse * 10 + number % 10
 number //= 10

 print(f"The reverse of the number is: {reverse}")

61. Write a program to check whether a given Number is Perfect


Number.

 number = int(input("Enter a number: "))


 sum = 0

 for i in range(1, number):
 if number % i == 0:
 sum += i

 if sum == number:
 print(f"{number} is a perfect number.")
 else:
 print(f"{number} is not a perfect number.")

62. Write a program to check if the given number is a Disarium


Number (11+ 72 + 53 = 1+ 49 + 125 = 175).

 number = int(input("Enter a number: "))


 digits = list(map(int, str(number)))
 sum = 0

 for i in range(len(digits)):
 sum += digits[i] ** (i + 1)

 if sum == number:
 print(f"{number} is a Disarium number.")
 else:
 print(f"{number} is not a Disarium number.")

63. Write a program to determine whether the given number is a


Harshad Number (If a number is divisible by the sum of its digits,
then it will be known as a Harshad Number).

 number = int(input("Enter a number: "))


 sum = sum(map(int, str(number)))

 if number % sum == 0:
 print(f"{number} is a Harshad number.")
 else:
 print(f"{number} is not a Harshad number.")

64. Write a program to Print Armstrong Number from 1 to 1000.

 for num in range(1, 1001):


 sum_of_powers = 0
 temp = num
 digits_count = len(str(num))

 while temp > 0:
 digit = temp % 10
 sum_of_powers += digit ** digits_count
 temp //= 10

 if sum_of_powers == num:
 print(num)

65. Write a program to Compute the Value of Xn.

 X = int(input("Enter the value of X: "))


 n = int(input("Enter the value of n: "))

 print(f"The value of {X} raised to the power of {n} is: {X**n}")

66. Write a program to Calculate the value of nCr.

 n = int(input("Enter value of n: "))


 r = int(input("Enter value of r: "))

 num = 1
 den = 1
 for i in range(1, n + 1):
 num *= i
 for i in range(1, r + 1):
 den *= i
 for i in range(1, n - r + 1):
 den *= i
 nCr = num // den
 print(f"The value of {n}C{r} is: {nCr}")

67. Write a program to generate the Fibonacci Series.

 n = int(input("Enter the number of terms: "))


 a, b = 0, 1
 for _ in range(n):
 print(a, end=" ")
 a, b = b, a + b

68. Write a program to check whether a given Number is


Palindrome or Not.

 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.")

69. Write a program to Check whether a given Number is an


Armstrong Number.

 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.")

70. Write a program to check weather a given number is prime


number or not.

 n = int(input("Enter a number: "))



 if n <= 1:
 print(f"{n} is not a prime number.")
 else:
 c=1
 for i in range(2, n):
 if n % i == 0:
 c=0
 break
 if c>0:
 print(f"{n} is a prime number.")
 else:
 print(f"{n} is not a prime number.")

71. Write a program to print all prime numbers from 1-500.

 for n in range(1, 501):


 c=1
 for i in range(2, n):
 if n % i == 0:
 c=0
 break
 if c and n > 1:
 print(n)

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)

73. Write a program to display the following pattern:

*****

*****

*****

*****

*****

 for i in range(5):
 for j in range(5):
 print("*",end=" ")
 print()

74. Write a program to display the following pattern:

**

***
****

*****

 for i in range(5):
 for j in range(5):
 print("*",end=" ")
 print()

75. Write a program to display the following pattern:

12

123

1234

12345

 for i in range(1, 6):


 for j in range(1, i + 1):
 print(j, end=" ")
 print()

76. Write a program to display the following pattern:

22

333

4444

55555

 for i in range(1, 6):


 for j in range(i):
 print(i, end=" ")
 print()

77. Write a program to display the following pattern:

A
BB

CCC

DDDD

EEEEE

 for i in range(65, 70):


 for j in range(i - 64):
 print(chr(i), end=" ")
 print()

78. Write a program to display the following pattern:

*****

****

***

**

 for i in range(5, 0, -1):


 print("* " * i)

79. Write a program to display the following pattern:

12345

1234

123

12

 for i in range(5, 0, -1):


 for j in range(1, i + 1):
 print(j, end=" ")
 print()
80. Write a program to display the following pattern:

***

*****

*******

*********

 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()

81. Write a program to display the following pattern:

232

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()

82. Write a program to display the following pattern:

*********
*******

*****

***

 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()

83. Write a program to display the following pattern (Pascal


Triangle):

1 1

1 2 1

1 3 3 1

1 4 6 4 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)

84. Write a program to display the following pattern:


1

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()

85. Write a program to display the following pattern:

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()

86. Write a program to display the following pattern:

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()

87. Write a program to display the following pattern:

ABCDEFGFEDCBA

ABCDEF FEDCBA

ABCDE 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()

88. Write a program to display the following pattern:

**********

**** ****

*** ***
** **

* *

 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()

89. Write a program to display the following pattern:

**

***

****

*****

*****

****

***

**

 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)

90. Write a program to display the following pattern:

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()

91. Write a program to display the following pattern:

0 0

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()
92. Write a program to display the following pattern:

1 1

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()

93. Write a program to display the following pattern:

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()

94. Write a program to display the following pattern:

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()

95. Write a program to display the following pattern:

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()

96. Write a program to display the following pattern:

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()

97. Write a program to Find the Sum of A.P Series.

 a=float(input(“Enter the first term (a): ”))


 d=float(input(“Enter the common difference (d): ”))
 n=int(input(“Enter the number of terms (n): ”))
 sum_ap=(n*a+(n-1)*d)/2
 print(f”The sum of the first {n} terms of the AP series is:
{sum_ap}”)

98. Write a program to Find the Sum of G.P Series.

 a=float(input(“Enter the first term (a): ”))


 r=float(input(“Enter the common ratio (r): ”))
 n=int(input(“Enter the number of terms (n): ”))
 sum_gp=0
 for I in range(n):
 sum_gp += a*(r**i)
 print(f”The sum of the first {n} terms of the AP series is:
{sum_gp}”)

99. Write a program to Find the Sum of H.P Series.

 n=int(input(“Enter the number of terms (n): ”))


 sum_

100. Write a program to print the following sequence of integers.


1, 2, 4, 8, 16, 32

 num = 1
 for i in range(6):
 print(num,end=",")
 num *= 2

Functions
101. Write a Python function to find the Max of three numbers.

 def max_of_three(num1, num2, num3):


 return max(num1, num2, num3)
 n1=int(input("Enter 1st number : "))
 n2=int(input("Enter 2nd number : "))
 n3=int(input("Enter 3rd number : "))

 print(max_of_three(n1,n2,n3))

102. Write a Python function to sum all the numbers in a list.


Sample List : (8, 2, 3, 0, 7)
Expected Output : 20

 def sum_of_list(numbers):
 return sum(numbers)

 lst = [1, 2, 3, 4, 5]
 print(sum_of_list(lst))

103. Write a Python function to multiply all the numbers in a list.


Sample List : (8, 2, 3, -1, 7)
Expected Output : -336

 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"

 s = input("Enter a string: ")


 reversed_s = s[::-1]
 print("Reversed string:", reversed_s)

105. Write a Python program calculate the factorial of a number


using lambda and reduce functions. The function accepts the
number as an argument.
 from functools import reduce
 factorial = lambda n: reduce(lambda x, y: x * y, range(1, n +
1)) if n > 0 else 1
 num = int(input("Enter a number: "))
 print(f"Factorial of {num} is: {factorial(num)}")

106. Write a Python function to check whether a number falls in a


given range.

 def inrange(num, start, end):


 return start <= num <= end

 num = int(input("Enter a number: "))
 start = int(input("Enter the start of the range: "))
 end = int(input("Enter the end of the range: "))

 if inrange(num, start, end):
 print(f"{num} is in the range {start} to {end}")
 else:
 print(f"{num} is not in the range {start} to {end}")

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.")

110. Write a Python function that checks whether a passed string is


palindrome or not.

 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)

112. Write a Python function to check whether a string is a


pangram or not.
Note: Pangrams are words or sentences containing every letter of
the alphabet at least once.
For example: "The quick brown fox jumps over the lazy dog"

 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 centimeter(feet, inches):


 total_inches = (feet * 12) + inches
 centimeters = total_inches * 2.54
 return centimeters

 feet = int(input("Enter height in feet: "))
 inches = int(input("Enter height in inches: "))

 centimeters = centimeter(feet, inches)
 print(f"Height in centimeters: {centimeters:.2f} cm")

115. Python function to Convert Celsius to Fahrenheit.

 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")

116. Python function to display all the Armstrong number from 1 to


n.

 def is_armstrong(num):
 num_str = str(num)
 num_digits = len(num_str)
 total = sum(int(digit) ** num_digits for digit in num_str)
 return total == num

 def armstrong_numbers(n):
 for num in range(1, n + 1):
 if is_armstrong(num):
 print(num)

 n = int(input("Enter a number: "))
 armstrong_numbers(n)

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}”)

118. Write a program to print Fibonacci Series using recursion.

 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=” ”)

119. Write a program to calculate sum of numbers 1 to N using


recursion.

 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}")

121. Write a program to print Tower of Hanoi using recursion.

 def tower_of_hanoi(n, source, target, auxiliary):


 if n == 1:
 print(f"Move disk 1 from {source} to {target}")
 return
 tower_of_hanoi(n - 1, source, auxiliary, target)
 print(f"Move disk {n} from {source} to {target}")
 tower_of_hanoi(n - 1, auxiliary, target, source)

 n = int(input("Enter the number of disks: "))
 tower_of_hanoi(n, 'A', 'C', 'B')

122. Python Program to Determine How Many Times a Given Letter


Occurs in a String Recursively

 def count_occurrences(string, letter, index=0):


 if index == len(string):
 return 0
 else:
 count = 1 if string[index] == letter else 0
 return count + count_occurrences(string, letter, index +
1)

 string = input("Enter a string: ")
 letter = input("Enter the letter to count: ")

 result = count_occurrences(string, letter)
 print(f"The letter '{letter}' occurs {result} times in the
string.")

123. Python Program to Find the Binary Equivalent of a Number


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 gcd(a, b):


 if b == 0:
 return a
 else:
 return gcd(b, a % b)
 a = int(input("Enter the first number: "))
 b = int(input("Enter the second number: "))
 result = gcd(a, b)
 print(f"The GCD of {a} and {b} is {result}")

125. Python Program to Find if a Number is Prime or Not Prime


Using Recursion.

 def is_prime(n, divisor=2):


 if n <= 1:
 return False
 if divisor == n:
 return True
 if n % divisor == 0:
 return False
 return is_prime(n, divisor + 1)
 n = int(input("Enter a number: "))
 if is_prime(n):
 print(f"{n} is a prime number.")
 else:
 print(f"{n} is not a prime number.")

126. Python Program to Find the Power of a Number Using


Recursion

 def power(base, exp):


 if exp == 0:
 return 1
 else:
 return base * power(base, exp - 1)

 base = int(input("Enter the base: "))
 exp = int(input("Enter the exponent: "))
 result = power(base, exp)
 print(f"The result of {base} raised to the power of {exp} is:
{result}")

127. Python Program to Check Whether a String is a Palindrome or


not 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.")

128. Python Program to Reverse a String Using Recursion.

 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.

Ex: Input: [‘45’,’88’,’9’] Output:[45,88,9]

 string_num=input(“Enter numbers as strings separated by


space: ”).split()
 integer_num= list(map(int, string_num))
 print(f”The list of integer numbers is : {integer_num}”)
130. WAP to find the largest element in the list using reduce
function.

 from functools import reduce


 number=list(map(int,input(“Enter number separated by
space: ”).split())
 largest = list(map(lambda x,y:x if x>y else y, number))
 print(f”The largest element in the list is : {largest}”)

131. WAP to compute the cube of all numbers in the given list using
map() function.

 number=list(map(int,input(“Enter number separated by


space: ”).split())
 cubes = list(map(lambda x: x**3, number))
 print(f”The cube of the numbers are : {cubes}”)

132. WAP to multiply two numbers using lambda function.

 multiply =lamba x,y:x*y


 num1=float(input(“”Enter the 1st number: “))
 num2=float(input(“”Enter the 2nd number: “))
 result=multiply(num1,num2)
 print(f”The product of {num1} and {num2} is: {result}”)

133. WAP to create a new list consisting of odd numbers from the
given list of numbers using filter() function.

 Number=list(map(int,input(“Enter number separated by


space: ”).split())
 Odd_number=list(filter(lambda x: x% 2!= 0, number)
 print(f”The list of odd numbers is: {odd_number}”)

134. WAP to compute the sum of all the elements of the list using
reduce() function.

 from functools import reduce


 number = list(map(int,(input(“Enter number separated by
space: ”) .split())
 sum_of_elements=reduce(lambda x,y: x+y, number)
 print(f”The sum of all elements in the list is :
{sum_of_elements}”)
Problem Solving Using Advance Python Lab

1. Write a program illustrating class definition and accessing class


members.
 from functools import reduce

 def sum_reduce(numbers):
 return reduce(lambda x, y: x + y, numbers)

 my_list = [1, 2, 3, 4, 5]
 print(sum_reduce(my_list))

2. Write a program to implement default constructor, parameterized


constructor, and destructor.
 class Person:
 def __init__(self, name="Unknown", age=0):
 self.name = name
 self.age = age
 print("Constructor called")

 def display_info(self):
 print(f"Name: {self.name}")
 print(f"Age: {self.age}")

 def __del__(self):
 print("Destructor called")

 person1 = Person()
 person1.display_info()

 person2 = Person("Ram", 25)
 person2.display_info()

 del person1
 del person2

3. Create a Python class named Rectangle constructed by a length and


width.
a. Create a method called area which will compute the area of a
rectangle.
 class Rectangle:
 def __init__(self, length, width):
 self.length = length
 self.width = width

 def area(self):
 return self.length * self.width

 rect = Rectangle(10, 5)
 print("Area of Rectangle:", rect.area())

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()

6. Create a class Employee that keeps a track of the number of


employees in an organization and also stores their name, designation
and salary details.
a. Write a method called getdata to take input (name, designation,
salary) from user.
b. Write a method called average to find average salary of all the
employees in the organization.
c. Write a method called display to print all the information of an
employee.
 class Employee:
 employee_count = 0
 total_salary = 0

 def __init__(self, name='', designation='', salary=0):
 self.name = name
 self.designation = designation
 self.salary = salary
 Employee.employee_count += 1
 Employee.total_salary += salary

 def getdata(self):
 self.name = input("Enter name: ")
 self.designation = input("Enter designation: ")
 self.salary = float(input("Enter salary: "))
 Employee.employee_count += 1
 Employee.total_salary += self.salary

 @classmethod
 def average(cls):
 if cls.employee_count > 0:
 return cls.total_salary / cls.employee_count
 return 0

 def display(self):
 print(f"Employee Name: {self.name}")
 print(f"Designation: {self.designation}")
 print(f"Salary: {self.salary}")

 emp1 = Employee()
 emp1.getdata()

 emp2 = Employee()
 emp2.getdata()

 emp1.display()
 emp2.display()

 avg_salary = Employee.average()
 print(f"Average Salary: {avg_salary:.2f}")
7. Create a Python class named Circle constructed by a radius. Use a
class variable to define the value of constant PI.
a. Write two methods to be named as area and circum to compute
the area and the perimeter of a circle respectively by using class
variable PI.
b. Write a method called display to print area and perimeter.
 class Circle:
 PI = 3.14159

 def __init__(self, radius):
 self.radius = radius

 def area(self):
 return Circle.PI * self.radius ** 2

 def circumference(self):
 return 2 * Circle.PI * self.radius

 circle = Circle(5)

 print("Area of the circle:", circle.area())
 print("Circumference of the circle:", circle.circumference())

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())
15. Write a program to illustrate the use of following built-in methods:
a. hasattr(obj,attr)
b. getattr(object, attribute_name [, default])
c. setattr(object, name, value)
d. delattr(class_name, name)

 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)

26. Write a program to compare two-person object based on their age by


overloading > operator.
 class Person:
 def __init__(self, name, age):
 self.name = name
 self.age = age
 def __gt__(self, other):
 if self.age > other.age:
 return True
 else:
 return False
 person1 = Person("Ram", 30)
 person2 = Person("Preeti", 19)
 if person1 > person2:
 print(f"{person1.name} is older than {person2.name}.")
 else:
 print(f"{person1.name} is not older than {person2.name}.")

27. Write a program to overload inoperator.


 class Student:
 def __init__(self, name, subjects):
 self.name = name
 self.subjects = subjects
 def __contains__(self, subject):
 return subject in self.subjects
 student = Student("Alice", ["Math", "Science", "English"])
 if "Math" in student:
 print("Math is in the list of subjects.")
 else:
 print("Math is not in the list of subjects.")
 if "History" in student:
 print("History is in the list of subjects.")
 else:
 print("History is not in the list of subjects.")

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)

34. Write a program that creates an iterator to print squares of numbers.


 class SquareIterator:
 def __init__(self, start, end):
 self.start = start
 self.end = end
 self.current = start
 def __iter__(self):
 return self
 def __next__(self):
 if self.current > self.end:
 raise StopIteration
 else:
 square = self.current ** 2
 self.current += 1
 return square
 iterator = SquareIterator(1, 5)
 for square in iterator:
 print(square)

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)

37. Write a program to create a generator to print the Fibonacci number.


 def fibonacci_generator():
 a, b = 0, 1
 while True:
 yield a
 a, b = b, a + b
 gen = fibonacci_generator()
 for _ in range(10):
 print(next(gen))
38. Write a program to create an arithmetic calculator using tkinter.
 import tkinter as tk
 def on_click(button_text):
 current = entry.get()
 if button_text == "=":
 try:
 result = str(eval(current))
 entry.delete(0, tk.END)
 entry.insert(tk.END, result)
 except Exception as e:
 entry.delete(0, tk.END)
 entry.insert(tk.END, "Error")
 elif button_text == "C":
 entry.delete(0, tk.END)
 else:
 entry.insert(tk.END, button_text)
 root = tk.Tk()
 root.title("Calculator")
 entry = tk.Entry(root, width=20, font=("Arial", 24),
borderwidth=2, relief="solid")
 entry.grid(row=0, column=0, columnspan=4)
 buttons = [
 ('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3),
 ('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('*', 2, 3),
 ('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('-', 3, 3),
 ('0', 4, 0), ('.', 4, 1), ('=', 4, 2), ('+', 4, 3),
 ('C', 5, 0)
 ]
 for (text, row, col) in buttons:
 button = tk.Button(root, text=text, font=("Arial", 18),
width=5, height=2,
 command=lambda text=text: on_click(text))
 button.grid(row=row, column=col)
 root.mainloop()

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()

40. Write a program to create a window that disappears automatically


after 5 seconds.
 import tkinter as tk
 def close_window():
 root.destroy()
 root = tk.Tk()
 root.title("Auto Close Window")
 label = tk.Label(root, text="This window will close in 5
seconds.")
 label.pack()
 root.after(5000, close_window)
 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()

43. Write a program to display a menu on the menu bar.


 import tkinter as tk
 from tkinter import messagebox
 def show_about():
 messagebox.showinfo("About", "This is a sample menu bar
program.")
 def open_file():
 messagebox.showinfo("Open File", "File opened
successfully.")
 def exit_program():
 root.quit()
 root = tk.Tk()
 root.title("Menu Bar Example")
 menu_bar = tk.Menu(root)
 file_menu = tk.Menu(menu_bar, tearoff=0)
 file_menu.add_command(label="Open", command=open_file)
 file_menu.add_separator()
 file_menu.add_command(label="Exit",
command=exit_program)
 menu_bar.add_cascade(label="File", menu=file_menu)
 help_menu = tk.Menu(menu_bar, tearoff=0)
 help_menu.add_command(label="About",
command=show_about)
 menu_bar.add_cascade(label="Help", menu=help_menu)
 root.config(menu=menu_bar)
 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)

47. Write a Program to convert a numpy array to a dataframe of given


shape.
 import numpy as np
 import pandas as pd
 numpy_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
 df = pd.DataFrame(numpy_array)
 print(df)

48. Write a program to count number of missing values in each column.


 import pandas as pd
 data = {'A': [1, 2, None, 4], 'B': [None, 2, 3, 4], 'C': [1, None,
None, 4]}
 df = pd.DataFrame(data)
 missing_values = df.isnull().sum()
 print(missing_values)
49. Write a program to replace missing values in a column of a dataframe
by the mean value of that column.
 import pandas as pd
 import matplotlib.pyplot as plt
 df = pd.read_csv('alphabet_stock_data.csv')
 df['Date'] = pd.to_datetime(df['Date'])
 start_date = '2020-01-01'
 end_date = '2020-12-31'
 filtered_df = df[(df['Date'] >= start_date) & (df['Date'] <=
end_date)]
 plt.figure(figsize=(10, 6))
 plt.plot(filtered_df['Date'], filtered_df['Open'], label='Opening
Price', color='blue')
 plt.plot(filtered_df['Date'], filtered_df['Close'], label='Closing
Price', color='red')
 plt.title('Alphabet Inc. Opening and Closing Stock Prices (2020)',
fontsize=14)
 plt.xlabel('Date', fontsize=12)
 plt.ylabel('Stock Price (in USD)', fontsize=12)
 plt.legend()
 plt.xticks(rotation=45)
 plt.tight_layout()
 plt.show()

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()

You might also like