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

code

The document contains multiple sets of Python code that implement various functionalities. Set 1 defines a stack class with operations like push, pop, display, and check if empty. Sets 2, 3, and 4 focus on managing peripheral records and student data using binary files with operations to add, display, and search records.

Uploaded by

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

code

The document contains multiple sets of Python code that implement various functionalities. Set 1 defines a stack class with operations like push, pop, display, and check if empty. Sets 2, 3, and 4 focus on managing peripheral records and student data using binary files with operations to add, display, and search records.

Uploaded by

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

SET 1

class Stack:

def __init__(self):

self.items = []

# 1. Push(item): Adds an item to the stack.

def Push(self, item):

self.items.append(item)

# 2. Pop(): Removes the top item from the stack and displays the item.

def Pop(self):

if not self.IsEmpty():

return self.items.pop()

else:

return "Stack is empty"

# 3. Display(): Displays all the items currently in the stack, starting from the top.

def Display(self):

if not self.IsEmpty():

print("Stack (top to bottom):")

for item in reversed(self.items):

print(item)

else:

print("Stack is empty")
# 4. IsEmpty(): Returns True if the stack is empty, otherwise False.

def IsEmpty(self):

return len(self.items) == 0

# Function to handle user input

def stack_operations():

stack = Stack()

while True:

print("\nStack Operations:")

print("1. Push(item)")

print("2. Pop()")

print("3. Display()")

print("4. IsEmpty()")

print("5. Exit")

choice = input("Enter your choice (1-5): ")

if choice == '1':

item = input("Enter the item to push onto the stack: ")

stack.Push(item)

print(f"Item {item} pushed onto the stack.")

elif choice == '2':

popped_item = stack.Pop()

if popped_item != "Stack is empty":

print(f"Popped item: {popped_item}")


else:

print(popped_item)

elif choice == '3':

stack.Display()

elif choice == '4':

if stack.IsEmpty():

print("The stack is empty.")

else:

print("The stack is not empty.")

elif choice == '5':

print("Exiting the program.")

break

else:

print("Invalid choice. Please enter a number between 1 and 5.")

# Run the stack operations with user input

stack_operations()

SET2
import pickle

# Define the peripheral class for better structure

class Peripheral:

def __init__(self, pid, name, category, price):


self.pid = pid

self.name = name

self.category = category

self.price = price

def __str__(self):

return f"PID: {self.pid}, Name: {self.name}, Category: {self.category}, Price: {self.price}"

# Function to add records to the binary file

def ADD():

try:

with open("PERIPHERALS.dat", "ab") as file:

pid = input("Enter Peripheral ID (PID): ")

name = input("Enter Peripheral Name: ")

category = input("Enter Category (Input/Output): ")

price = float(input("Enter Price: "))

peripheral = Peripheral(pid, name, category, price)

pickle.dump(peripheral, file)

print("Record added successfully!")

except Exception as e:

print(f"Error adding record: {e}")

# Function to display peripherals with price > 15000

def DISPLAY():

try:
with open("PERIPHERALS.dat", "rb") as file:

print("Displaying peripherals where Price > 15000:")

found = False

while True:

try:

peripheral = pickle.load(file)

if peripheral.price > 15000:

print(peripheral)

found = True

except EOFError:

break

if not found:

print("No peripherals found with price greater than 15000.")

except Exception as e:

print(f"Error displaying records: {e}")

# Function to search for a peripheral by PID that falls under the Output category

def SEARCH(pid):

try:

with open("PERIPHERALS.dat", "rb") as file:

found = False

while True:

try:

peripheral = pickle.load(file)

if peripheral.pid == pid and peripheral.category.lower() == "output":

print(f"Found peripheral: {peripheral}")


found = True

break

except EOFError:

break

if not found:

print(f"No output peripheral found with PID: {pid}")

except Exception as e:

print(f"Error searching record: {e}")

# Menu-driven program

def menu():

while True:

print("\nMenu:")

print("1. ADD - Add a new record")

print("2. DISPLAY - Display all peripherals with Price > 15000")

print("3. SEARCH - Search for a peripheral with PID and category Output")

print("4. Exit")

choice = input("Enter your choice: ")

if choice == "1":

ADD()

elif choice == "2":

DISPLAY()

elif choice == "3":

pid = input("Enter Peripheral ID (PID) to search: ")


SEARCH(pid)

elif choice == "4":

print("Exiting the program.")

break

else:

print("Invalid choice. Please try again.")

# Main entry point to the program

if __name__ == "__main__":

menu()

SET 3
import pickle
# Define a class to store student data
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def __str__(self):
return f"{self.name}: {self.marks}"
# Function to write student data to binary file
def write_to_file(filename):
num_students = int(input("Enter the number of
students: "))

with open(filename, 'wb') as file:


for _ in range(num_students):
name = input("Enter student name: ")
marks = float(input(f"Enter marks for {name}:
"))
student = Student(name, marks)
pickle.dump(student, file)
# Function to display students who scored more
than 95 marks
def display_high_scorers(filename):
with open(filename, 'rb') as file:
print("\nStudents who scored more than 95
marks:")
while True:
try:
student = pickle.load(file)
if student.marks > 95:
print(student)
except EOFError:
break
# Main program
def main():
filename = 'marks.dat'

write_to_file(filename) # Get user input and


write to file
display_high_scorers(filename) # Display high
scorers
if __name__ == '__main__':
main()

set 4

import pickle

# Define the peripheral class for better structure


class Peripheral:
def __init__(self, pid, name, category, price):
self.pid = pid
self.name = name
self.category = category
self.price = price
def __str__(self):
return f"PID: {self.pid}, Name: {self.name},
Category: {self.category}, Price: {self.price}"

# Function to add records to the binary file


def ADD():
try:
with open("PERIPHERALS.dat", "ab") as file:
pid = input("Enter Peripheral ID (PID): ")
name = input("Enter Peripheral Name: ")
category = input("Enter Category
(Input/Output): ")
price = float(input("Enter Price: "))

peripheral = Peripheral(pid, name, category,


price)
pickle.dump(peripheral, file)
print("Record added successfully!")
except Exception as e:
print(f"Error adding record: {e}")

# Function to display peripherals with price > 15000


def DISPLAY():
try:
with open("PERIPHERALS.dat", "rb") as file:
print("Displaying peripherals where Price >
15000:")
found = False
while True:
try:
peripheral = pickle.load(file)
if peripheral.price > 15000:
print(peripheral)
found = True
except EOFError:
break
if not found:
print("No peripherals found with price
greater than 15000.")
except Exception as e:
print(f"Error displaying records: {e}")

# Function to search for a peripheral by PID that falls


under the Output category
def SEARCH(pid):
try:
with open("PERIPHERALS.dat", "rb") as file:
found = False
while True:
try:
peripheral = pickle.load(file)
if peripheral.pid == pid and
peripheral.category.lower() == "output":
print(f"Found peripheral:
{peripheral}")
found = True
break
except EOFError:
break
if not found:
print(f"No output peripheral found with
PID: {pid}")
except Exception as e:
print(f"Error searching record: {e}")

# Menu-driven program
def menu():
while True:
print("\nMenu:")
print("1. ADD - Add a new record")
print("2. DISPLAY - Display all peripherals with
Price > 15000")
print("3. SEARCH - Search for a peripheral with
PID and category Output")
print("4. Exit")

choice = input("Enter your choice: ")

if choice == "1":
ADD()
elif choice == "2":
DISPLAY()
elif choice == "3":
pid = input("Enter Peripheral ID (PID) to
search: ")
SEARCH(pid)
elif choice == "4":
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

# Main entry point to the program


if __name__ == "__main__":
menu()

You might also like