Python MySQL Solutions
Python MySQL Solutions
Page 1 Solutions
Question 9
Write a program in Python to create a binary file 'STUD.dat' with the following student
details:
Roll_No, Name, Class, Marks, Grade.
Assume max marks = 100 and assign the grade using the criteria provided.
Solution:
import pickle
def write_to_file():
with open("STUD.dat", "wb") as f:
n = int(input("Enter number of students: "))
for _ in range(n):
roll_no = int(input("Enter Roll No: "))
name = input("Enter Name: ")
class_ = input("Enter Class: ")
marks = int(input("Enter Marks: "))
grade = 'F'
if marks >= 90:
grade = 'A'
elif marks >= 80:
grade = 'B'
elif marks >= 70:
grade = 'C'
elif marks >= 60:
grade = 'D'
elif marks >= 50:
grade = 'E'
student = {'Roll_No': roll_no, 'Name': name, 'Class': class_, 'Marks': marks, 'Grade':
grade}
pickle.dump(student, f)
def read_from_file():
try:
with open("STUD.dat", "rb") as f:
while True:
student = pickle.load(f)
print(student)
except EOFError:
pass
write_to_file()
read_from_file()
Question 10
Solution:
stack = []
def push(element):
stack.append(element)
print(f"{element} pushed to stack.")
def pop():
if not stack:
print("Stack is empty.")
else:
print(f"{stack.pop()} popped from stack.")
def display():
print("Stack:", stack)
while True:
print("1. PUSH
2. POP
3. DISPLAY STACK
4. EXIT")
choice = int(input("Enter your choice: "))
if choice == 1:
element = input("Enter element to push: ")
push(element)
elif choice == 2:
pop()
elif choice == 3:
display()
elif choice == 4:
break
else:
print("Invalid choice.")
Question 11
Write a program in Python to generate a random number between two numbers using user-
defined function.
Solution:
import random
Question 12
Solution:
def fibonacci(n):
fib = [0, 1]
for i in range(2, n):
fib.append(fib[-1] + fib[-2])
return fib[:n]
Page 2 Solutions
Solutions to the questions on Page 2 will be added here.
Page 3 Solutions
Solutions to the questions on Page 3 will be added here.
Page 4 Solutions
Solutions to the questions on Page 4 will be added here.