0% found this document useful (0 votes)
13 views34 pages

ACFrOgAq5EYCrQ5nXqJWrcQ4yzz5-NYV8 T7zj b4jkY2vsDrV9CN3dzoxP6wQYbyN2G78mB7nxysG1hV1pHTxhGW15Zo vxTlzrDG9ZSNllZH0GtDC2l6pEs-x2O2lANvTEXofxZ9mFy4jWt7PI

Uploaded by

tharun.v
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views34 pages

ACFrOgAq5EYCrQ5nXqJWrcQ4yzz5-NYV8 T7zj b4jkY2vsDrV9CN3dzoxP6wQYbyN2G78mB7nxysG1hV1pHTxhGW15Zo vxTlzrDG9ZSNllZH0GtDC2l6pEs-x2O2lANvTEXofxZ9mFy4jWt7PI

Uploaded by

tharun.v
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

COMPUTER

SCIENCE

PRACTICAL FILE

Done By:- Aayush Nawale


Class:- 12B

1
CERTIFICATE

This is to certify that Aayush Nawale of Class


XII-B of Global Indian International School has
successfully completed his/her Practical file in
Computer Science for the AISSCE as
prescribed by CBSE in the year 2024-2025.

Date: ___________
Roll No.: _______________

Teacher’s Sign Examiner

Principal’s Sign

2
ACKNOWLEDGEMENT

In the accomplishment of this practical file


successfully, many people have bestowed upon me their
blessings and the heart pledged support. I thank all the
people who have been concerned with my work.

I would like to sincerely thank my Computer Science


teacher Ms Rupa Mathew, whose valuable guidance has
been the one that helped me complete this and make it a
success. Her suggestions and instructions have served
as the major contribution towards the completion of this
project.

I would like to thank my Principal Ms Dipti Joshna,


for providing me with all the facilities that were
required.

Then I would like to extend my gratitude towards all


the teaching and non-teaching staff of Global Indian
International School and my parents who supported me
in completing my practical file.

INDEX
Sr. No. Title of Program Pg. No.

3
1. PRINT THE WORD- NEGATIVE/POSITIVE/ZERO 6

2. CHECK WHETHER NUMBER IS EVEN OR NOT 6

3. FIND FACTORIAL OF A NUMBER 6

4. CHECK WHETHER STRING IS A PALINDROME 7

5. PRINT SUM OF EVEN NUMBERS FROM 1 TO 7 7

6. PRINT SUM OF INTEGERS FROM N TO 2*N 8

7. PRINT N TERMS OF FIBONACCI SERIES 8

8. PRINT MINIMUM VALUE IN A LIST 9

9. CHECK WHETHER VALUE EXISTS IN A DICTIONARY 9

10. DICE SIMULATOR 10

11. SIMPLE INTEREST FINDER 10

12. DOLLAR TO RUPEES CONVERTER 10

13. CUBE FUNCTION AND COMPARING LENGTH 11

14. FUNCTION TO GENERATE 3 RANDOM NUMBERS BETWEEN 2 11


NUMBERS
15. FUNCTIONS TO CHECK IF 2 STRINGS HAVE SAME LENGTH 12

16. RETURN NTH ROOT OF A NUMBER 13

17. RANDOM NUMBER GENERATOR WITH N DIGITS 13

18. FUNCTION TO RETURN NUMBER WITH MINIMUM ONE’S DIGIT 14

19. DISPLAY EACH WORD SEPARATED BY # 14

20. DISPLAY NUMBER OF VOWELS/ CONSONANTS/ UPPERCASE/ 15


LOWERCASE CHARACTER IN THE FILE AND REMOVE ALL THE
LINES THAT CONTAIN ‘a’ IN A FILE AND WRITE IT TO ANOTHER
FILE
21. FUNCTION TO DISPLAY WORDS OF A TEXT FILE WHICH ARE 16
LESS THAN 4 CHARACTERS
22. PROGRAM TO CREATE A DUPLICATE TEXT FILE WHERE 17
SEQUENCE OF CONSECUTIVE BLANK SPACES IS REPLACED
BY A SINGLE SPACE
23. PROGRAM TO COUNT THE WORDS “to” and “the” IN TEXT FILE 17
“Poem.txt”

4
24. FUNCTION TO COUNT THE NUMBER OF A AND M 18

25. PROGRAM TO COUNT THE NUMBER OF UPPERCASE 18


ALPHABETS
26. PROGRAM TO COPY ONE FILE TO ANOTHER 19

27. PROGRAM TO APPEND ONE FILE TO ANOTHER 19

28. PROGRAM STORE UPPER AND LOWER CASE CHARACTERS IN 20


DIFFERENT FILES
29. FUNCTION TO COUNT THE NUMBER OF LINES STARTING WITH 21
A
30. FUNCTION TO DISPLAY THE LINES HAVING 5 WORDS 22

31. PROGRAM TO CREATE BINARY FILE WITH NAME AND ROLL 22


NUMBER AND SEARCH FOR A GIVEN ROLL NUMBER
32. PROGRAM TO CREATE A BINARY FILE WITH ROLL NUMBER 23
NAME MARKS AND UPDATE THE MARKS
33. FUNCTION TO INPUT DATA FOR A RECORD AND COUNT THE 24
NUMBER OF BOOKS FOR GIVEN AUTHOR
34. FUNCTION TO CREATE A FILE ‘Athletic.dat’ WHICH CONTAINS 25
RECORDS FROM ‘sports.dat’ WHERE EVENT NAME IS ‘athletics’
35. CREATE A FUNCTION ‘staffcreate()’ AND ’searchstaff()’ 26

36. PYTHON PROGRAM TO READ GIVEN CSV WITH TAB 27


DELIMITER
37. FUNCTION TO CREATE CSV FILE WITH USER-ID AND 28
PASSWORD AND SEARCH THE PASSWORD AND FUNCTION TO
COPY THE CONTENTS OF ONE FILE TO ANOTHER EXCEPT
THE LINE STARTING WITH CHECK
38. PYTHON PROGRAM TO IMPLEMENT A STACK USING LIST 29
DATA STRUCTURE
39. MENU DRIVEN PYTHON PROGRAM TO FIND SUM, 30
DIFFERENCE, MULTIPLICATION AND DIVISION OF 2 NUMBERS

40. MENU DRIVEN PYTHON PROGRAM TO IMPLEMENT STACK 32


USING LIST DATA STRUCTURE

1. PRINT THE WORD- NEGATIVE/POSITIVE/ZERO


AIM:
Write a program to print the word- negative/positive/zero according to whether the
variable is less than zero, more than zero or zero.
SOURCE CODE:
num=int(input('Enter a number'))
if num>0:

5
print('POSITIVE')
elif num<0:\
print('NEGATIVE')
else:
print('ZERO')

SAMPLE OUTPUT:

2. CHECK WHETHER NUMBER IS EVEN OR NOT


AIM:
Write a program that returns True if the input number is an even number, False
otherwise.
SOURCE CODE:
num=int(input('Enter number:'))
if num%2==0:
print("TRUE")
else:
print("FALSE")

SAMPLE OUTPUT:

3.FIND FACTORIAL OF A NUMBER


AIM:
Write a program to find factorial of a number
SOURCE CODE:
num=int(input("number:"))
x=1
for i in range(1,num+1):
x=x*i

6
print(x)

SAMPLE OUTPUT:

4.CHECK WHETHER STRING IS A PALINDROME


AIM:
Write a program to check if a string is palindrome or not
SOURCE CODE:
x=str(input("enter string:"))
if x==x[::-1]:
print("string is palindrome")
else:
print("not a palindrome")
SAMPLE OUTPUT:

5. PRINT SUM OF EVEN NUMBERS FROM 1 TO 7


AIM:
Write a program to find sum of even numbers from 1 to 7
SOURCE CODE:
s= 0
for num in range(1, 8):
if num % 2 == 0:
s += num
print("Sum of even numbers:", s)

SAMPLE OUTPUT:

7
6. PRINT SUM OF INTEGERS FROM N TO 2*N
AIM:
Write a program that reads an integer N from the keyboard computes and displays
the sum of the numbers from N to (2*N) if N is non negative. If N is a negative
number, then it’s the sum of the numbers from (2*N) to N. The starting and ending
points are included in the sum.

SOURCE CODE:
N = int(input("Enter: "))
if N>=0:
x = sum(range(N, 2*N+1))
else:
x = sum(range(2*N, N+1))
print("The sum of the numbers:", x)

SAMPLE OUTPUT:

7. PRINT N TERMS OF FIBONACCI SERIES


AIM:
Write a Program to enter the number of terms and to print the Fibonacci Series.
SOURCE CODE:
n = int(input("How many terms? "))
a, b = 0, 1
count = 0
if n <= 0:
print("Please enter a positive integer")
elif n==1:
print('Fibonacci sequence:',a)
else:
print("Fibonacci sequence:")
while count < n:

8
print(a)
x = a + b
a = b
b = x
count+= 1

SAMPLE OUTPUT:

8. PRINT MINIMUM VALUE IN A LIST


AIM:
Program to find minimum value in a list.
SOURCE CODE:
n = eval(input("Enter a list: "))
x = min(n)
print("Minimum value :", x)

SAMPLE OUTPUT:

9.CHECK WHETHER VALUE EXISTS IN A DICTIONARY


AIM:
Program to check whether a value exists in dictionary
SOURCE CODE:
def check(x):
if x in my_dict.values():
print(f"The value exists in the dictionary.")
else:

9
print(f"The value does not exist in the
dictionary.")
x = int(input("Value you want to check:"))
check(x)
SAMPLE OUTPUT:

10.DICE SIMULATOR
AIM:
Write a random number generator that generates random numbers between 1 and 6
(simulates a dice)

SOURCE CODE:
import random
print (random.randint(1,6))
SAMPLE OUTPUT:
4

11.FIND SIMPLE INTEREST


AIM:
Write a program to find simple interest using a user defined function with
parameters and with return value.
SOURCE CODE:
def simpleinterest(principal, rate, time):
x=(principal * rate * time)/100
return x
SAMPLE OUTPUT:

12.CONVERT DOLLARS TO RUPEES


AIM:
Write a function that takes an amount in dollars and convert the same to Rupees.

10
SOURCE CODE:
def convert(USD):
inr=USD/83.99
return inr
USD=float(input("Amount ins USD:"))
SAMPLE OUTPUT:
4233.00

13:
AIM:
Write a program to have the following functions:
a) A function that takes a number as an argument and calculates a cube for it. The
function does not return a value. If there is no value passed to the function
in function call, the function should calculate cube of 2
b) A function that takes two char arguments and returns True if both arguments
are equal otherwise False.

SOURCE CODE:
def cube(X=2):
Y = X** 3
print("The cube of {X} is: {Y}")

def equal(X, Y):


return X == Y
SAMPLE OUTPUT:
Are the numbers equal? True
Are the numbers equal? False
The cube of 2 is: 8
The cube of 3 is: 27

14.
AIM:
Write a function that receives two numbers and generates a random number from
that range. Using this function, the main program should be able to print three

11
numbers randomly.

SOURCE CODE:
import random
def generator(start, end):
return random.randint(start, end)
x = int(input("Enter the start: "))
y = int(input("Enter the end: "))
print("Three random numbers:")
for i in range(4):
z = generator(x, y)
print(z)
SAMPLE OUTPUT:
Three random numbers:
25
22
30

15.
AIM:
Write a function that receives two string arguments and checks whether they are
same length strings(returns True else False).

SOURCE CODE:
def length(x, y):
return len(x) == len(y)
x=input('Enter String 1:')
y=input("Enter String 2: ")
length(x,y)
SAMPLE OUTPUT:
The two strings have the same length.

12
16.
AIM:
Write a function namely nthRoot() that receives two parameters x and n and returns
nth root of x. i.e x 1/n . The default value of n is 2.
SOURCE CODE:
def nthRoot(x, n = 2):
return x ** (1/n)

x = int(input("Enter the value of x:"))


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

y = nthRoot(x, n)
print("The", n, "th root of", x, "is:", y)

z = nthRoot(x)
print("The square root of", x, "is:", z)
SAMPLE OUTPUT:

17.
AIM:
Write a function that takes a number n and then returns a randomly
generated number having exactly n digits(not starting with zero).

SOURCE CODE:
import random
def generate_number(n):
x = 10 ** (n - 1)
y = (10 ** n) - 1
return random.randint(x, y)

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

13
random_number = generate_number(n)
print("Random number:", random_number)
SAMPLE OUTPUT:

18.
AIM:
Write a function that takes two numbers and returns the number that has the
minimum one’s digit.
SOURCE CODE:
def min_digit(num1, num2):
x = num1 % 10
y = num2 % 10
if x < y:
return x
else:
return y
SAMPLE OUTPUT:

19.
AIM:
Read a text file line by line and display each word separated by a #
SOURCE CODE:
def hash(filename):
try:
with open(filename, 'r') as file:
for i in file:
words = i.strip().i()
print('#'.join(words))
except FileNotFoundError:

14
print(f"The file '{filename}' does not exist.")

SAMPLE OUTPUT:

20.
AIM:
Read a text file and display the number of vowels/consonants/uppercase/lowercase
characters in the file. Remove all the lines that contain the character 'a' in a file and
write it to another file.

SOURCE CODE:
def filter_file(input_file, output_file):
vowels = 'aeiouAEIOU'
vowels= consonants = uppercase = lowercase= 0

try:
with open(input_file, 'r') as file, open(output_file,
'w') as new_file:
for line in file:

for char in line:


if char.isalpha():
if char in vowels:
vowels += 1
else:
consonants += 1
if char.isupper():
uppercase += 1
elif char.islower():
lowercase += 1

if 'a' not in line and 'A' not in line:

15
new_file.write(line)

print(f"Vowels: {vowels}")
print(f"Consonants: {consonants}")
print(f"Uppercase characters: {uppercase}")
print(f"Lowercase characters: {lowercase}")

except FileNotFoundError:
print(f"The file '{input_file}' does not exist.")

SAMPLE OUTPUT:

21.
AIM:
Write a function DISPLAYWORDS() in python to read lines from a text file
STORY.TXT and display those words which are less than 4 characters

SOURCE CODE:
def DISPLAYWORDS():
try:
with open('STORY.TXT', 'r') as file:
for line in file:
words = line.strip().split()
for word in words:
if len(word)<4:
print(word)
except FileNotFoundError:
print("The file 'STORY.TXT' does not exist.")

SAMPLE OUTPUT:

16
22.
AIM:
Write a program that reads a text file and creates another file that is identical except
that every sequence of consecutive blank spaces is replaced by a single space.

SOURCE CODE:
def remove_extra_spaces(input_file, output_file):
file=open(input_file, 'r')
new_file= open(output_file, 'w+')
for i in file:
x = ' '.join(i.split())
new_file.write(x + '\n')
SAMPLE OUTPUT:

23.
AIM:
Write a program to count the words “to” and "the” present in a text file “Poem.txt”.
SOURCE CODE:
def count_words_in_file(poem):
to_count = 0
the_count = 0
file=open(poem.txt, 'r')
for line in file:
words = line.lower().split()
to_count += words.count("to")
the_count += words.count("the")
print(f"The word 'to' appears {to_count} times.")
print(f"The word 'the' appears {the_count} times.")
SAMPLE OUTPUT:

17
24.
AIM:
Write a function AMCount() in Python, which should read each character of a text
file STORY.TXT. It should count and display the occurrence of alphabet A and M
including (small case a and m).
SOURCE CODE:
def AMCount():
a_count=0
m_count=0
file=open('STORY.TXT', 'r')
for i in file:
for char in i:
if char == 'A' or char == 'a':
a_count+= 1

elif char == 'M' or char == 'm':


m_count+= 1

print(f"The letter 'A' or 'a' appears {a_count} times.")


print(f"The letter 'M' or 'm' appears {m_count} times.")
SAMPLE OUTPUT:

25.
AIM:
Write a program to count the number of uppercase alphabets present in a text file
Article.txt.

SOURCE CODE:
def count_uppercase_characters(filename):

18
uppercase_count = 0
file= open(filename, 'r')
for i in file:
for x in i:
if x.isupper():
uppercase_count += 1
print(f"The number of uppercase alphabets in
'{filename}' is: {uppercase_count}")
SAMPLE OUTPUT:

26.
AIM:
Write a program that copies one file to another. Have the program read the file
names from the user.
SOURCE CODE:
source= input("Enter name of source file: ")
destination= input("Enter name of destination file: ")
src=open(source, 'r')
dest=open(destination, 'w')
for line in src:
dest.write(line)
print(f"File '{source}' has been copied to '{destination}'.")
SAMPLE OUTPUT:
source: destination:

27.
AIM:
Write a program that appends the contents of one file to another. Have the program
read the file names from the user.

SOURCE CODE:

19
def append_file_contents():
source= input("Entername of source file: ")
destination= input("Enter name of destination file: ")
src= open(source, 'r')
dest=open(destination, 'a')
for line in src:
dest.write(line)
print(f"Contents of '{source}' have been appended to
'{destination}'.")

SAMPLE OUTPUT:

28.
AIM:
Write a program that reads characters from the keyboard one by one. All lower
case characters get stored inside the file LOWER, all upper case characters fet
stored inside the file UPPER and all other characters get stored inside the file
OTHERS.
SOURCE CODE:
lower= open("LOWER.txt", 'w')
upper = open("UPPER.txt", 'w')
others = open("OTHERS.txt", 'w')
ans = 'y'
while ans == 'y':
x = input("Enter a character: ")
if x.islower():
lower.write(x + "\n")
elif x.isupper():
upper.write(x + "\n")
else:
others.write(x + "\n")
ans = input("Want to enter a character? (y/n): ")

20
SAMPLE OUTPUT:
Enter a character: e
Want to enter a character? (y/n): y
Enter a character: A
Want to enter a character? (y/n): y
Enter a character: D

29.
AIM:
Write a function in Python to count and display the number of lines starting with A
present in the text file LINES.TXT.
SOURCE CODE:
def count_lines(file_name):
count = 0
file= open(file_name, 'r')
for i in file:
if i.strip().startswith('A'):
count += 1
print(count)

count_lines("LINES.TXT")

SAMPLE OUTPUT:
3

30.
AIM:
Write a function SHOW_WORDS() in Python to read the content of a text file
“NOTES.TXT” and display only such lines of the file which have exactly 5 words in
them.

SOURCE CODE:
def Show_words(file_name):
file= open(file_name, 'r')

21
for i in file:
words = i.strip().split()
if len(words) == 5:
print(i.strip())
Show_words('NOTES.TXT')
SAMPLE OUTPUT:
This is a sample file.

31.
AIM:
Create a binary file with name and roll number. Search for a given roll number and
display the name, if not found display appropriate message.

SOURCE CODE:
import pickle
def create_file(name, roll_number):
with open('students.bin', 'ab') as file:
pickle.dump((name, roll_number), file)
def search_roll_number(roll_number):
file= open('students.bin', 'rb')
while True:
try:
name, number = pickle.load(file)
if number == roll_number:
return name
except EOFError:
break
return None
name = search_roll_number(1)
if name is not None:
print(f'Name: {name}')
else:
print('Roll number not found.')
SAMPLE OUTPUT:

22
32.
AIM:
Create a binary file with roll number, name and marks. Input a roll number and
update the marks.
SOURCE CODE:
import pickle
def create_binary_file(filename):
data = []
while True:
roll_number = input("Enter roll number (or 'exit' to
stop): ")
if roll_number.lower() == 'exit':
break
name = input("Enter name: ")
marks = input("Enter marks: ")
data.append((roll_number, name, marks))
file= open(filename, 'wb')
pickle.dump(data, file)
print(f"Data has been written to {filename}.")

def update_marks(filename, roll_number, new_marks):


try:
file= open(filename, 'rb')
data = pickle.load(file)
for i, (roll, name, marks) in data:
if roll == roll_number:
data[i] = (roll, name, new_marks)
break
else:
print("Roll number not found.")
return

23
file= open(filename, 'wb')
pickle.dump(data, file)
print(f"Marks for roll number {roll_number} have
been updated to {new_marks}.")

except FileNotFoundError:
print(f"The file '{filename}' does not exist.")

SAMPLE OUTPUT:

33.
AIM:
A binary file “Book.dat” has structure [Book_No,Book_Name, Author, Price].
a) Write a user defined function CreateFile() to input data for a record and add to
Book.dat
b) Write a function CountRec(Author) in Python which accepts the Author name as
parameter and count and return number of books by the given author are stored
in the binary file “Book.dat”
SOURCE CODE:
import pickle

def CreateFile(filename):
file=open(filename, 'wb')
while True:
book_no = input("Enter Book Number (or 'exit' to stop):
")
if book_no.lower() == 'exit':
break
else:
book_name = input("Enter Book Name: ")
author = input("Enter Author Name: ")
price = float(input("Enter Price: "))

24
record = (book_no, book_name, author, price)
pickle.dump(record, file)
print(f"Data has been written to {filename}.")

def CountRec(filename, author):


count = 0
try:
file= open(filename, 'rb')
while True:
try:
record = pickle.load(file)
if record[2] == author:
count += 1
except EOFError:
break
return count
except FileNotFoundError:
print(f"The file '{filename}' does not exist.")
return 0
SAMPLE OUTPUT:

34.
AIM:
A file sports.dat contains information in the following format: Event – Participant
Write a function that would read contents from file sports.dat and creates a file
named Atheletic.dat copying only those records from sports.dat where the event
name is “Athletics”.
SOURCE CODE:
def filter_records(input_file, output_file):
f_in= open(input_file, 'r')
with open(output_file, 'w') as f_out:
for line in f_in:

25
event, participant = line.strip().split(' - ')
if event == 'Athletics':
f_out.write(line)
filter_records('sports.dat', 'Athletic.dat')
SAMPLE OUTPUT:

35.
AIM:
Consider the definition of the dictionary STAFF below.
Staff={‘staffcode’:___, ‘name’: ______}.
Create a method – staffcreate() . Ask user to enter details for the dictionary and
store the same in STAFF.dat.
Create another method – searchstaff() to search and display the content from
staff.dat

SOURCE CODE:
import pickle
def search_and_display_staff(staff_code):
found = False
try:
file = open("staff.dat", "rb")
while True:
staff_data = pickle.load(file)
if staff_data['Staffcode'] == staff_code:
print("Staffcode:",
staff_data['Staffcode'])
print("Name:", staff_data['Name'])
found = True
except EOFError:
if found == False:

26
print("End of file reached. No such records
found.")
else:
print("Search Successful")
file.close()
search_and_display_staff('S0105')

SAMPLE OUTPUT:

36.
AIM:
Write a python program to read the given csv file with tab delimiter.
SOURCE CODE:
import csv

with open("example.csv", 'r', newline='') as file:


reader = csv.reader(file, delimiter='\t')
for row in reader:
print(row)
SAMPLE OUTPUT:

37.
AIM:
Create a CSV file by entering user-id and password, read and search the password
for given user id.
Write a function that reads a csv file and creates another csv file with the same
content except the lines beginning with ‘check’.

27
SOURCE CODE:
import csv
def create_csv_file(filename):
file= open(filename, 'w', newline='')
writer = csv.writer(file)
while True:
user_id = input("Enter User ID (or 'exit' to stop):
")
if user_id.lower() == 'exit':
break
password = input("Enter Password: ")
writer.writerow([user_id, password])
print(f"Data has been written to {filename}.")

def search_password(filename, user_id):


try:
file= open(filename, 'r')
reader = csv.reader(file)
for row in reader:
if row[0] == user_id:
print(f"Password for User ID '{user_id}':
{row[1]}")
return
print(f"User ID '{user_id}' not found.")
except FileNotFoundError:
print(f"The file '{filename}' does not exist.")

def filter_csv_file(input_filename, output_filename):


infile= open(input_filename, 'r')
outfile=open(output_filename, 'w', newline='')
reader = csv.reader(infile)
writer = csv.writer(outfile)
for row in reader:
if not row[0].startswith('check'):

28
writer.writerow(row)
print(f"Filtered data has been written to
{output_filename}.")

SAMPLE OUTPUT:

38.
AIM:
Write a python program to implement a stack using a list data structure.
SOURCE CODE:
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
print(f"Pushed: {item}")
def pop(self):
if self.is_empty():
raise IndexError("Pop from empty stack")
item = self.stack.pop()
print(f"Popped: {item}")
return item
def peek(self):
if self.is_empty():
raise IndexError("Peek from empty stack")
return self.stack[-1]
def is_empty(self):
return len(self.stack) == 0
def size(self):

29
return len(self.stack)
def display(self):
print("Stack contents:", self.stack)

SAMPLE OUTPUT:

39.
AIM:
Write a menu driven program to find the sum, difference, multiplication and division
of two numbers
SOURCE CODE:
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y

def divide(x, y):


if y == 0:
raise ValueError("Cannot divide by zero.")
return x / y
def main():
while True:
print("\nMenu:")
print("1. Sum")
print("2. Difference")

30
print("3. Multiplication")
print("4. Division")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '5':
print("Exiting the program.")
break
if choice in ['1', '2', '3', '4']:
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
result = add(num1, num2)
print(f"The sum of {num1} and {num2} is:
{result}")
elif choice == '2':
result = subtract(num1, num2)
print(f"The difference of {num1} and {num2}
is: {result}")
elif choice == '3':
result = multiply(num1, num2)
print(f"The multiplication of {num1} and
{num2} is: {result}")
elif choice == '4':
result = divide(num1, num2)
print(f"The division of {num1} by {num2}
is: {result}")
else:
print("Invalid choice. Please enter a number
between 1 and 5.")

SAMPLE OUTPUT:

31
40.
AIM:
Write a Menu driven python program to implement a Stack using a list data-
structure.
SOURCE CODE:
def peek(self):
if self.is_empty():
print("Stack is empty! Cannot peek.")
return None
return self.stack[-1]
def is_empty(self):
return len(self.stack) == 0
def size(self):
return len(self.stack)
def display(self):
if self.is_empty():
print("Stack is empty.")
else:
print("Stack contents:", self.stack)
def main():
stack = Stack()
while True:
print("\nMenu:")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Check if Empty")

32
print("5. Size")
print("6. Display")
print("7. Exit")
choice = input("Enter your choice (1-7): ")
if choice == '1':
item = input("Enter the item to push: ")
stack.push(item)
elif choice == '2':
stack.pop()
elif choice == '3':
top_item = stack.peek()
if top_item is not None:
print(f"Top item is: {top_item}")
elif choice == '4':
if stack.is_empty():
print("Stack is empty.")
else:
print("Stack is not empty.")
elif choice == '5':
print(f"Size of the stack: {stack.size()}")
elif choice == '6':
stack.display()
elif choice == '7':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a number
between 1 and 7.")
SAMPLE OUTPUT:

33
34

You might also like