harshitsinghpython.py
harshitsinghpython.py
print("Hello World!")
quotient = a // b
remainder = a % b
print("Quotient:", quotient)
print("Remainder:", remainder)
average = (a + b + c) / 3
marks = []
for i in range(5):
total = sum(marks)
print("Percentage:", percentage)
square_area = side ** 2
s = (a + b + c) / 2 # Semi-perimeter
# Cube
cube_volume = side ** 3
cube_surface_area = 6 * (side ** 2)
# Cuboid
# Cylinder
# Cone
# Sphere
# Trapezium
trapezium_area = 0.5 * (a + b) * h
# Rhombus
rhombus_area = 0.5 * d1 * d2
# Parallelogram
# 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
print("After swapping (without third variable): a =", a, "b =",
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
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
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)
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}”)
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}”)
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.
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 ”)
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!")
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")
LOOPS:
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}”)
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
22
333
4444
55555
A
BB
CCC
DDDD
EEEEE
*****
****
***
**
12345
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()
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()
*********
*******
*****
***
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 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)
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()
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()
**********
**** ****
*** ***
** **
* *
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()
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()
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()
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 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))
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))
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.")
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)
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")
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:
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}”)
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}")
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}")
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.
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.
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()
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()
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'))
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()
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)
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)
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)
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()
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()