Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

PythonLabFile Vanshi F-1

Uploaded by

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

PythonLabFile Vanshi F-1

Uploaded by

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

JAGAN INSTITUTE OF MANAGEMENT STUDIES

SECTOR – 5, ROHINI, NEW DELHI

(Affiliated to)
GURU GOBIND SINGH INDRAPRASTHA UNIVERSITY
SECTOR – 16 C, DWARKA, NEW DELHI

PYTHON

Submitted To: M s . Ankita Chopra Submitted By: Mohit


Gautam Assistant Professor (IT) Enrolment No.:
35250404423
MCA 1st Year (Section - A)
2nd Semester
ACKNOWLEDGEMENT
I take this opportunity to present my vote of thanks to my faculty who really acted as
pillars to help my way throughout the execution of lab exercises that has led to
successful and satisfactory completion of the study of Subject PYTHON
PROGRAMMING.
I feel great sense of gratitude for Ms. Ankita Chopra under whose guidance and
motivation this work has been performed.
I would also like to express my thanks to all lab assistants for giving me the
opportunity to work under their esteemed guidance. This project would not have been
completed without their guidance and coordination.
The inspiration of the faculty members of the Information Technology Department
of JIMS Rohini (Sec-5) enabled me to make a thorough study of these subjects.

Student Name: Mohit Gautam


Enrollment No.: 35250404423
CERTIFICATE
This is certified to be the bona fide work of the student, Name: Mohit Gautam
Enrollment No.: 35250404423 for the purpose of subject Python Programming of
nd
MCA, 2 semester under the supervision of Ms.Ankita Chopra during the academic
year 2023-2025.

Ms. Ankita Chopra


Assistant Professor
(IT) JIMS, Rohini
Index
1 Read a number n and compute n+nn+nnn
2 Print all Numbers in a Range Divisible by a Given Number
3 Accept three distinct digits and print all possible
combinations from the digits
4 Program to Find the Sum of Digits in a Number
5 Program to Find the Smallest Divisor of an Integer (other
than 1)
6 Print all integers that are not divisible by either 2 or 3 and
lie between 1 and 50.
7 Accept a number n and prints an identity matrix of nXn
8 Compute the Value of 1+2+3+….+n
9 Compute euler’s number. Use the Formula: e = 1 + 1/1! +
1/2!
+ …… 1/n!
10 Read Print Prime Numbers in a range using Sieve of
Eratosthenes (using User defined function)
11 Write a program that encrypts a message by adding a key
value
to every character. (Caesar Cipher) (Input: “abc” . output:
“def” , Add 3 to each character)
12 Write a program to parse an email id to print from which
email server it was sent and when. (
input: From abc.jims@gmail.com Sun
Jan 27 20:29:15 2023, output : The email has been
sent through gmail.com It was sent on Sun Jan 27 20:29:15
2023)
13 Program to find the second largest element in a list ‘Num’.
14 Write a Python code to delete all odd numbers and negative
numbers from a given numeric list.
15 Python Program to Find Element Occurring Odd Number of
Times in a List.
16 Python Program to Check if a String is a Palindrome or Not.
17 Check if the Substring is present in a Given String.
18 Write a program to determine whether a given string has
balanced parenthesis or not.
19 Display Letters which are in the First String but not in the
Second.
20 Write a program that reads a string and then prints a string
that capitalizes every other letter in the string. E.g., corona
becomes cOrOnA.
21 Python Program to Remove the Given Key from a
Dictionary.
22 Python Program to Count the Frequency of Words
Appearing in a String Using a Dictionary.
23 WAP to store students information like admission number,
roll
number, name and marks in a dictionary and display
information on the basis of admission number.

24 Python Program to Find the Total Sum of a Nested List


Using Recursion.
25 Python Program to Read a String from the User and Append
it
into a File.
26 Python Program to Count the Occurrences of a Word in a
Text File.
27 Write a program to compare two files and display total
number of lines in a file.
28 Accept list and key as input and find the index of the key in
the list using linear search.
29 Write a program to arrange a list on integer elements in
ascending order using bubble sort technique.
10,51,2,18,4,31,13,5,23,64,29
30 Create a Class which Performs Basic Calculator Operations.
31 Every time a vote is cast the name of the candidate is
appended to the data structure. Print the names of
candidates who received maximum vote in lexicographical
order and if there
is a tie print lexicographically smaller name.
32 Create Birthday Reminder Application to notify users using
file handling and exception handling.
33 Create a class “Time” and initialize it with hrs and mins.
1. Make a method addTime which should take two time
object and add them. E.g.- (6 hour and 35 min)+(2 hr and
12 min) is (8 hr and 47 min)
2. Make a method showTime which should print the time.
3. Make a method showMinute which shoulddisplay the
total minutes in the Time. E.g.- (2 hr 6 min) should
display 126 minutes.
34 Write a Python class which has two methods get_String and
print_String. get_String accept a string from the user and
print_String print the string in upper case.
35 Create a class “GrandMother” with a subclass “Mother”
with a subclass “Daughter”. All the three classes to have
there own constructors. The object of only “Daughter”
class to be made
to fetch all the details of Grandmother and mother.
36 Create a class “Parent” and a subclass “Child”. The
“Parent” holds a constructor with two parameters name
and age and also one method print() that prints name and
age. The “child to have only one constructor that send the
value to parent
constructor and calls print() from its constructor only.
Note: the object of only “Child” class to be created.
37 Write a program to create an abstract class “Animal” that
holds three declaration functions based on their
characteristics. Create four subclasses – “Mammals”,

“Reptiles”, “birds”, and “amphibians” inherited from


“Animal” class.
38 Implement ATM simulation system displaying its operations
using object oriented features.
39 Python Program to Append, Delete and Display Elements
of a List Using Classes.
1. Read a number n and compute n+nn+nnn
n = int(input('enter a number: '))

num = 0

for i in range(1, n+1):

p = n ** i

num = num +

p print(num)

2. Print all Numbers in a Range Divisible by a Given Number


stran = int(input('input the starting range : '))

endran = int(input('input the ending range :

')) num = int(input('enter a number : '))

for i in range(stran,

endran+1): if i % num ==

0:

print(i)
3. Accept three distinct digits and print all possible combinations from
the digits
arr = [2,4,5]

for i in range(3):

for j in range(3):

for k in range(3):

if ( i!=j and j!=k and i!

=k):

print(arr[i],arr[j],arr[k])
4. Program to Find the Sum of Digits in a Number
num = int(input('enter number: '))

sum = 0

temp = num

while temp >

0:

digit = temp %

10 sum += digit

temp //= 10

print(sum)
5. Program to Find the Smallest Divisor of an Integer (other than 1)
num = int(input("Enter an integer: "))

divisor = 2

while divisor <= num:

if num % divisor == 0:

op = divisor

break

else:

divisor += 1

print(f"The smallest divisor of",num," (other than 1) is:",op)


6. Print all integers that are not divisible by either 2 or 3 and lie between 1 and 50.
for i in range(1,51):

if i%2!=0 and i%3!

=0: print(i)
7. Accept a number n and prints an identity matrix of nXn

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

for i in range(0, n):

for j in range(0, n):

if i == j:

print("1", sep=" ", end="

") else:

print("0", sep=" ", end="

") print()

8. Compute the Value of 1+2+3+….+n


n = int(input('enter a number:'))

q=0

for i in

range(1,n+1): q =

q+i

print(q)
9. Compute euler’s number. Use the Formula: e = 1 + 1/1! + 1/2! + ……1/n!

def fact(n):

fact = 1

for i in range(1, n + 1):

fact = fact * i

return fact

print('euler formula')

num = int(input('enter a number:

')) op=0

for i in range(1,num+1):

div = 1/fact(i)

op = op + div

print('the eular sol is

',op)
10. Read Print Prime Numbers in a range using Sieve of Eratosthenes (using User
defined function)

def is_prime(num):
if num <= 1:
return False

for i in range(2, int(num**0.5) +


1): if num % i == 0:
return False
return True

start_range = int(input("Enter the starting range: "))


end_range = int(input("Enter the ending range: "))

print('Prime numbers in the range' , start_range ,'to' ,end_range,' are:')


for num in range(start_range, end_range + 1):
if is_prime(num):
print(num, end=" ")
11. Write a program that encrypts a message by adding a key value to every character.
(Ca esar Cipher) (Input: “abc” . output: “def” , Add 3 to each character)

def encrypt(message,
keys):
encrypted_message = ""
for char in message:
if char.isalpha(): # Check if the character is a letter
shift = (ord(char) + keys - ord('a') if char.islower() else ord(char) + keys - ord('A')) %
26
encrypted_char = chr(shift + ord('a') if char.islower() else shift + ord('A'))
encrypted_message += encrypted_char
else:
encrypted_message += char # Keep non-alphabetic characters unchanged
return encrypted_message

input_message = "abc"
key = 3
output_message = encrypt(input_message, key)
print(f"Input: \"{input_message}\"")
print(f"Output: \"{output_message}\"")
12. Write a program to parse an email id to print from which email server it was sent
and when. ( input: From abc.jims@gmail.com Sun Jan 27 20:29:15 2023,
output : The email has been sent through gmail.com It was sent on Sun Jan 27 20:29:15
2023)

import re

def parse_email(email_id):
pattern = re.compile(r'From\s+(\S+@\S+)\s+\w+\s+(\w+\s+\d+\s+\d+:\d+:\d+\s+\
d+)') match = pattern.search(email_id)

if match:
server = match.group(1)
timestamp = match.group(2)

return f"The email has been sent through {server}\nIt was sent on {timestamp}"
else:
return "Invalid email ID format"

email_id = "From abc.jims@gmail.com Sun Jan 27 20:29:15


2023" result = parse_email(email_id)
print(result)
13. Program to find the second largest element in a list ‘Num’.

list1 = [10, 20, 4, 100 , 99]

mx = max(list1[0], list1[1])

secondmax = min(list1[0],

list1[1]) n = len(list1)

for i in range(2,n):

if list1[i] > mx:

secondmax =

mx mx = list1[i]

elif list1[i] > secondmax and

\ mx != list1[i]:

secondmax = list1[i]

elif mx == secondmax and \

secondmax != list1[i]:

secondmax = list1[i]

print("Second highest number is :

",\ str(secondmax))
14. Write a Python code to delete all odd numbers and negative numbers from a
given numeric list.

def filter_numbers(nums):

return [num for num in nums if num % 2 == 0 and num >= 0]

# Example usage:

numbers = [1, 2, 3, 4, -5, 6, -7, 8, 9, -10]

filtered_numbers = filter_numbers(numbers)

print(filtered_numbers)
15. Python Program to Find Element Occurring Odd Number of Times in a List.

def find_odd_occurrence(numbers):

element_count = {}

for number in numbers:

if number not in

element_count:

element_count[number] = 1

else:

element_count[number] +=

1 odd_occ_elements = []

for element in element_count:

if element_count[element] % 2 != 0:

odd_occ_elements.append(element)

return odd_occ_elements

numbers = [1, 2, 1, 3, 1, 2, 3, 2,4]

odd_elements = find_odd_occurrence(numbers)

print("Elements occuring odd number of times in given list: ", odd_elements)


16. Python Program to Check if a String is a Palindrome or Not.

def palindrome(string):

reversed_string =

''.join(reversed(string)) return string

== reversed_string

print(palindrome("racecar"))

print(palindrome("hello"))
17. Check if the Substring is present in a Given String .

s = "Hello, World!"

substring =

"World"

if s.find(substring) != -1:

print("The substring is present in the

string.") else:

print("The substring is not present in the string.")


18. Write a program to determine whether a given string has balanced
parenthesis or not.
def balanced(string):

stack = []

mapping = {')': '(', ']': '[', '}': '{'}

for char in string:

if char in

mapping.values():

stack.append(char)

elif char in mapping.keys():

if not stack or stack.pop() !=

mapping[char]: return False

else:

continue

return not stack

print(balanced("(hi[world])"))

print(balanced("(hi[world])]"))
19. Display Letters which are in the First String but not in the Second.

first_string = input("Enter the first string: ")

second_string = input("Enter the second

string: ") first_set = set(first_string)

second_set = set(second_string)

difference_set = first_set -

second_set result_string =

"".join(difference_set)

print("The letters in the first string but not in the second string:", result_string)
20. Write a program that reads a string and then prints a string that capitalizes
every other letter in the string. E.g., corona becomes cOrOnA.

def capitalize(input_string):

output_string = ""

for i, char in

enumerate(input_string): if i % 2

== 0:

output_string +=

char.upper() else:

output_string +=

char return

output_string

input_string = "corona"

output_string = capitalize(input_string)

print(output_string)
21. Python Program to Remove the Given Key from a Dictionary.

my_dict = {'a': 1, 'b': 2, 'c': 3,

'd': 4} keys_to_remove = ['b',

'c']

for key in

keys_to_remove: del

my_dict[key]

print(my_dict)
22. Python Program to Count the Frequency of Words Appearing in a String
Using a Dictionary.

input_string = "This is a test string

" word_list = input_string.split()

frequencies = {}

for word in word_list:

if word in frequencies:

frequencies[word] += 1

else:

frequencies[word] = 1

print("frequencies are:")

print(frequencies)
23. WAP to store students’ information like admission number, roll number,
name and marks in a dictionary and display information on the basis of
admission number.

class Student:

marks = []

def getData(self, rn, name, m1, m2, m3):

Student.rn = rn

Student.name = name

Student.marks.append(m1)

Student.marks.append(m2)

Student.marks.append(m3)

def displayData(self):

print ("Roll Number is: ",

Student.rn) print ("Name is: ",

Student.name) print ("Marks are:

", Student.marks) print ("Total

Marks are: ", self.total())

print ("Average Marks are: ", self.average())

def total(self):

return (Student.marks[0] + Student.marks[1] +Student.marks[2])

def average(self):

return ((Student.marks[0] + Student.marks[1] +Student.marks[2])/3)

r = int (input("Enter the roll number:

")) name = input("Enter the name: ")

m1 = int (input("Enter the marks in the first subject: "))


m2 = int (input("Enter the marks in the second

subject: ")) m3 = int (input("Enter the marks in the

third subject: ")) s1 = Student()

s1.getData(r, name, m1, m2,

m3) s1.displayData()
24. Python Program to Find the Total Sum of a Nested List Using Recursion.

def

flatten(seq):

for item in

seq:

if isinstance(item, list):

yield from

flatten(item)

else:

yield item

nested_list = [[4, 5], [7, 8, [20]],

100] total_sum =

sum(flatten(nested_list))

print(total_sum)
25. Python Program to Read a String from the User and Append It into a File.

fname = input("Enter file name: ")

file3=open(fname,"a")

c=input("Enter string to append: \

n"); file3.write("\n")

file3.write(

c)

file3.close(

print("Contents of appended

file:"); file4=open(fname,'r')

line1=file4.readline() while(line1!

=""):

print(line1)

line1=file4.readline()

file4.close()
26. Python Program to Count the Occurrences of a Word in a Text File.
f=

open('file.txt', 'r')

count = 0

word = input("Enter the word to be

counted: ") for line in f:

words =

line.split() for i

in words:

if i == word:

count += 1

print("The word", word, "occurs", count, "times")


27. Write a program to compare two files and display the total number of lines in a
file.

with open("readme") as f1, open("readme") as


f2: count = 0
for line in f1:
count +=
1 for line
in f2:
count += 1
print("Total number of lines: ", count)
28. Accept list and key as input and find the index of the key in the list using
linear search.
def linear_Search(list1, n, key):

for i in range(0, n):

if (list1[i] == key):

return i

return -1

list1 = [1 ,3, 5, 7, 9]

key = 7

n = len(list1)

res = linear_Search(list1, n,

key) if(res == -1):

print("Element not
found") else:

print("Element found at index: ", res)


29. Write a program to arrange a list on integer elements in ascending order
using bubble sort technique.
10, 51, 2, 18, 4, 31, 13, 5, 23, 64, 29

def bubble_sort(arr):

arr_len = len(arr)

for i in range(arr_len-1):

flag = 0

for j in range(0, arr_len-i-1):

if arr[j] > arr[j+1]:

arr[j+1], arr[j] = arr[j],

arr[j+1] flag = 1

if flag == 0:

brea

k return arr

arr = [10, 51, 2, 18, 4, 31, 13, 5, 23, 64, 29]

print("List sorted with bubble sort in ascending order: ", bubble_sort(arr))


30. Create a Class which Performs Basic Calculator Operations

class Calculator:
def init
(self):
pass

def add(self, num1, num2):


return num1 + num2

def subtract(self, num1,


num2): return num1 - num2

def multiply(self, num1,


num2): return num1 * num2

def divide(self, num1,


num2): if num2 == 0:
return "Error! Division by
zero." else:
return num1 / num2

def mod(self, num1, num2):

return num1 % num2

calc = Calculator()

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))
operation = input("Enter the operation (+, -, *, /,
%): ")

if operation == '+':
print("Result:", calc.add(num1, num2))
elif operation == '-':
print("Result:", calc.subtract(num1,
num2)) elif operation == '*':
print("Result:", calc.multiply(num1,
num2)) elif operation == '/':
print("Result:", calc.divide(num1,
num2)) elif operation == '%':
print("Result:", calc.mod(num1,
num2)) else:
print("Invalid operation. Please enter +, -, *, or /.")
31. Every time a vote is cast the name of the candidate is
appended to the data structure. Print the names of candidates
who received maximum vote in lexicographical order and if there
is a tie print lexicographically smaller name.

class
VoteCounter:
def init (self):
self.votes = {}
def cast_vote(self,
candidate_name): if
candidate_name in self.votes:
self.votes[candidate_name] += 1
else:
self.votes[candidate_name] = 1
def get_max_votes_candidates(self):
max_votes = max(self.votes.values())
max_vote_candidates = [candidate for candidate, votes
in
self.votes.items() if votes ==
max_votes] return
sorted(max_vote_candidates)[0]
counter = VoteCounter()
votes_casted = ["Alice", "Bob", "Alice", "Charlie", "Bob", "Bob", "Alice"]
# Record the votes
for vote in votes_casted:
counter.cast_vote(vote)

# Get the candidate(s) with the maximum


votes winner =
counter.get_max_votes_candidates()
print("Winner(s) with maximum votes:",
winner)
32. Create Birthday Reminder Application to notify users
using file handling and exception handling.

import datetime
class
BirthdayReminder:
def init (self,
filename):
self.filename = filename
def add_birthday(self, name,
date): try:
with open(self.filename, 'a') as file: file.write(f"{name},
{date}\n")
print("Birthday added successfully!")
except Exception as e:
print(f"Error occurred while adding birthday:
{e}") def check_birthdays(self):
try:
today = datetime.date.today().strftime('%d-
%m') with open(self.filename, 'r') as file:
for line in file:
name, date =
line.strip().split(',') if date ==
today:
print(f"Today is {name}'s birthday!")
except Exception as e:
print(f"Error occurred while checking birthdays:

{e}") reminder = BirthdayReminder("birthdays.txt")

while True:
print("\n1. Add
Birthday") print("2.
Check Birthdays")
print("3. Exit")
choice = input("Enter your choice: ")

if choice == '1':
name = input("Enter name: ")
date = input("Enter date (DD-MM): ")
reminder.add_birthday(name, date)
elif choice == '2':
reminder.check_birthdays()
elif choice == '3':
print("Exiting..
.") break
else:
print("Invalid choice! Please enter a valid option.")
33. Create a class “Time” and initialize it with hrs and mins.
1.Make a method addTime which should take two time object and
add them. E.g.- (6 hour and 35 min)+(2 hr and 12 min) is (8 hr and
47 min)
2.Make a method showTime which should print the time.
3.Make a method showMinute which shoulddisplay the total
minutes in the Time. E.g.- (2 hr 6 min) should display 126
minutes.

class Time: def init


(self, hrs, mins):
self.hrs = hrs
self.mins = mins

@staticmethod
def addTime(t1, t2):
total_hrs = t1.hrs +
t2.hrs
total_mins = t1.mins + t2.mins

if total_mins >= 60:


total_hrs += 1
total_mins -= 60
return Time(total_hrs,
total_mins) def showTime(self):
print(f"{self.hrs} hr and {self.mins} min")

def showMinute(self):
total_minutes = self.hrs * 60 + self.mins
print(f"Total minutes: {total_minutes}")

# Take input from the user for time values


hrs1 = int(input("Enter hours for time 1: "))
mins1 = int(input("Enter minutes for time 1:
")) hrs2 = int(input("Enter hours for time 2: "))
mins2 = int(input("Enter minutes for time 2:
"))
# Create Time objects with user input
t1 = Time(hrs1,
mins1) t2 =
Time(hrs2, mins2)

# Add two time objects


result = Time.addTime(t1, t2)
print("Result of addition:", end="
") result.showTime()
result.showMinute()
34. Write a Python class which has two methods get_String and
print_String. get_String accept a string from the user and
print_String print the string in upper case.

class
StringManipulator:
def init (self):
self.input_string = ""

def get_String(self):
self.input_string = input("Enter a string: ")

def
print_String(self)
: if
self.input_string:
print("String in uppercase:",
self.input_string.upper()) else:
print("No string provided. Please use get_String method first.")

manipulator = StringManipulator()
manipulator.get_String()
manipulator.print_String()
35. Create a class “GrandMother” with a subclass “Mother” with a
subclass “Daughter”. All the three classes to have there own
constructors. The object of only “Daughter” class to be made to
fetch all the details of Grandmother and mother.

class GrandMother:
def init (self, grandmother_name):
self.grandmother_name = grandmother_name
class Mother(GrandMother):
def init (self, grandmother_name, mother_name):
super(). init (grandmother_name)
self.mother_name = mother_name
class Daughter(Mother):
def init (self, grandmother_name, mother_name,
daughter_name): super(). init (grandmother_name,
mother_name) self.daughter_name = daughter_name
def fetch_details(self):
return f"Grandmother: {self.grandmother_name}, Mother:
{self.mother_name}, Daughter: {self.daughter_name}"

grandmother_name = input("Enter grandmother's name: ")


mother_name = input("Enter mother's name: ")
daughter_name = input("Enter daughter's name: ")

daughter = Daughter(grandmother_name, mother_name, daughter_name)

print(daughter.fetch_details())
36. Create a class“Parent” and a subclass “Child”. The “Parent”
holds a constructor with two parameters name and age and also
one method print() that prints name and age. The“child to have
only one constructor that send the value to parent constructor and
calls print() from its constructor only. Note: the object of only
“Child” class to be created.

class Parent:
def init (self, name,
age):
self.name =
name self.age =
age

def print_info(self):
print(f"Name: {self.name}, Age: {self.age}")

class Child(Parent):
def init (self, name,
age): super(). init
(name, age)
self.print_info() # Call print_info method from Parent class within Child
constructor

name = input("Enter name:


") age = int(input("Enter
age: "))

child = Child(name, age)


37. Write a program to create an abstract class “Animal” that holds
three declaration functions based on their characteristics. Create
four subclasses – “Mammals”, “Reptiles”, “birds”, and
“amphibians” inherited from “Animal” class.
from abc import ABC, abstractmethod

class Animal(ABC):

@abstractmethod
def
movement(self):
pass

@abstractmethod
def habitat(self):
pass

@abstractmethod
def sound(self):
pass

class Mammals(Animal):
def movement(self):
return "Mammals can walk, run, or swim."

def habitat(self):
return "Mammals live in various habitats including forests, deserts, and
oceans."

def sound(self):
return "Mammals produce a variety of sounds including roars, howls, and
grunts."

class
Reptiles(Animal):
def
movement(self):
return "Reptiles move by crawling, slithering, or
swimming." def habitat(self):
return "Reptiles inhabit diverse environments such as deserts,
rainforests, and oceans."

def sound(self):
return "Reptiles can produce sounds but they are generally not as vocal
as mammals or birds."

class Birds(Animal):
def
movement(self):
return "Birds move by walking, hopping, flying, or swimming."

def habitat(self):
return "Birds are found in various habitats including forests,
grasslands, and wetlands."

def sound(self):
return "Birds are known for their diverse vocalizations such as
songs, chirps, and calls."

class
Amphibians(Animal):
def movement(self):
return "Amphibians have diverse modes of movement including hopping,
crawling, and swimming."

def habitat(self):
return "Amphibians are commonly found near water bodies such
as ponds, lakes, and streams."

def sound(self):
return "Some amphibians can produce sounds like croaks or
chirps, especially during mating season."

# Example usage:
mammal =
Mammals() reptile =
Reptiles() bird =
Birds()
amphibian = Amphibians()
print("=== Mammals ===")
print(mammal.movement())
print(mammal.habitat())
print(mammal.sound())
print("\n=== Reptiles ===")
print(reptile.movement())
print(reptile.habitat())
print(reptile.sound())
print("\n=== Birds ===")
print(bird.movement())
print(bird.habitat())
print(bird.sound()) print("\
n=== Amphibians ===")
print(amphibian.movement()
) print(amphibian.habitat())
print(amphibian.sound())
38. Implement ATM simulation system displaying its
operations using object oriented features.

class ATM:
def init (self, balance=0):
self.balance = balance
def
check_balance(self):
print(f"Your current balance is: $
{self.balance}") def deposit(self, amount):
self.balance += amount
print(f"${amount} deposited successfully.")
self.check_balance()
def withdraw(self,
amount): if amount <=
self.balance:
self.balance -= amount
print(f"${amount} withdrawn successfully.")
self.check_balance()
else:
print("Insufficient funds.")
initial_balance = float(input("Enter initial balance:
")) atm = ATM(initial_balance)
print("Welcome to the ATM!")
atm.check_balance() # Check initial balance
deposit_amount = float(input("Enter amount to deposit: "))
atm.deposit(deposit_amount)
withdraw_amount = float(input("Enter amount to withdraw: "))
atm.withdraw(withdraw_amount)
39. Python Program to Append, Delete and Display Elements of
a List Using Classes.

class
ListManager:
def init (self):
self.my_list = []

def append_element(self, element):


self.my_list.append(element)
print(f"Element '{element}' appended successfully.")

def delete_element(self,
element): if element in
self.my_list:
self.my_list.remove(element)
print(f"Element '{element}' deleted successfully.")
else:
print(f"Element '{element}' not found in the list.")

def
display_elements(self):
if self.my_list:
print("Elements in the
list:") for element in
self.my_list:
print(element
) else:
print("List is
empty.") manager =
ListManager() while
True:
print("\n1. Append
Element") print("2. Delete
Element") print("3. Display
Elements") print("4. Exit")
choice = input("Enter your choice: ")

if choice == '1':
element = input("Enter element to append: ")
manager.append_element(element)
elif choice == '2':
element = input("Enter element to delete: ")
manager.delete_element(element)
elif choice == '3':
manager.display_elements()
elif choice == '4':
print("Exiting...")
break
else:
print("Invalid choice! Please enter a valid option.")

You might also like