PYTHON ASSIGNMENT 2
1. Implement a multi-threading program in Python where:
• One thread prints numbers from 1 to 10 with a delay of 1 second each.
• Another thread prints letters from ‘A’ to ‘J’ with a delay of 1 second each. • Use
thread synchronization to ensure both threads complete execution before exiting.
Program:
import threading import
time
# Function to print numbers from 1 to 10 with a delay of 1 second
def print_numbers(event): for i in range(1, 11):
print(i)
time.sleep(1)
event.set() # Signal that the number thread has completed #
Function to print letters from 'A' to 'J' with a delay of 1 second
def print_letters(event): for i in range(10): print(chr(65
+ i)) # chr(65) is 'A' time.sleep(1) event.set() # Signal
that the letter thread has completed def main():
event_numbers = threading.Event() event_letters =
threading.Event()
thread_numbers = threading.Thread(target=print_numbers, args=(event_numbers,))
thread_letters = threading.Thread(target=print_letters, args=(event_letters,))
# Starting both threads thread_numbers.start()
thread_letters.start() event_numbers.wait()
event_letters.wait() print("Both threads have
completed execution.") if __name__ ==
"__main__": main() import threading import
time
# Function to print numbers from 1 to 10 with a delay of 1 second
def print_numbers(event): for i in range(1, 11):
print(i)
time.sleep(1)
event.set() # Signal that
the number thread has
completed # Function to
print letters from 'A' to 'J'
with a delay of 1 second
def print_letters(event):
for i in range(10):
print(chr(65 + i)) #
chr(65) is 'A'
time.sleep(1)
event.set() # Signal that the letter thread has completed
# Main function def
main():
# Event to synchronize threads
event_numbers = threading.Event()
event_letters = threading.Event()
# Creating threads for printing numbers and letters thread_numbers =
threading.Thread(target=print_numbers, args=(event_numbers,)) thread_letters =
threading.Thread(target=print_letters, args=(event_letters,))
# Starting both threads
thread_numbers.start() thread_letters.start()
# Wait for both threads to finish
event_numbers.wait() event_letters.wait()
print("Both threads have completed execution.") if
__name__ == "__main__": main()
2. Write a Python program that demonstrates exception handling by:
• Taking user input for division and handling ZeroDivisionError, ValueError, and a user-
defined exception called NegativeNumberError (raised when the input number is
negative).
• Using assert statements to ensure inputs are positive.
PROGRAM:
class NegativeNumberError(Exception):
"""Custom exception for negative numbers."""
pass
def divide_numbers():
try:
# Taking user input num1 = input("Enter the
numerator: ") num2 = input("Enter the denominator: ")
# Ensuring inputs are numeric assert num1.isdigit(),
"Numerator must be a number!" assert num2.isdigit(),
"Denominator must be a number!"
# Convert to integers
num1 = int(num1) num2
= int(num2)
Assert that inputs are positive
assert num1 >= 0, "Numerator must be a positive number!"
assert num2 > 0, "Denominator must be a positive number!"
# Raise an exception if the number is negative if num1 < 0 or
num2 < 0: raise NegativeNumberError("Input number cannot be
negative.")
# Perform the division result = num1 / num2
print(f"Result of {num1} divided by {num2} is: {result}")
except ValueError: print("Invalid input! Please enter
numeric values.") except ZeroDivisionError:
print("Error: Cannot divide by zero.") except
NegativeNumberError as e:
print(f"Negative number error: {e}")
except AssertionError as e:
print(f"Assertion Error: {e}") except
Exception as e: print(f"An unexpected error
occurred: {e}") if __name__ == "__main__":
divide_numbers()
OUTPUT:
3. Write a Python program that:
• Creates a text file named student_data.txt and writes student records(name, age, and
marks) into it.
• Opens the file in read mode and displays its contents using read(),readline(), and
readlines().
• Implements error handling for file operations using try-except blocks to handle file-
related exceptions (e.g., FileNotFoundError, IOError).
• Renames the file to student_records.txt and then deletes it using appropriate Python
functions.
• Uses the pickle module to serialize and deserialize a dictionary containing student data.
PROGRAM:
import os
import pickle
# Student data dictionary
student_data = {
'Student1': {'name': 'Diksha', 'age': 19, 'marks': 90},
'Student2': {'name': 'Aditi', 'age': 19, 'marks': 90},
}
# 1. Create a text file named student_data.txt and write student records into it.
try:
with open('student_data.txt', 'w') as file:
for student, data in student_data.items():
file.write(f"{student}: Name: {data['name']}, Age: {data['age']}, Marks:
{data['marks']}\n")
print("Student data written to student_data.txt.")
except IOError as e:
print(f"Error writing to file: {e}")
# 2. Open the file in read mode and display its contents using read(), readline(), and readlines().
try:
with open('student_data.txt', 'r') as file:
# Using read()
content = file.read()
print("\nContents of student_data.txt using read():")
print(content)
# Using readline()
file.seek(0) # Move cursor back to the start
print("\nContents of student_data.txt using readline():")
print(file.readline()) # Read the first line
# Using readlines()
file.seek(0) # Move cursor back to the start
print("\nContents of student_data.txt using readlines():")
lines = file.readlines()
for line in lines:
print(line, end='')
except FileNotFoundError as e:
print(f"Error: The file does not exist. {e}")
except IOError as e:
print(f"Error reading file: {e}")
# 3. Renaming the file to student_records.txt and then deleting it.
try:
os.rename('student_data.txt', 'student_records.txt')
print("\nFile renamed to student_records.txt.")
# Deleting the file
os.remove('student_records.txt')
print("File student_records.txt deleted.")
except FileNotFoundError as e:
print(f"Error: The file to rename or delete does not exist. {e}")
except IOError as e:
print(f"Error renaming or deleting file: {e}")
# 4. Use the pickle module to serialize and deserialize the student data dictionary.
try:
# Serialize the dictionary and save it to a file
with open('student_data.pkl', 'wb') as pickle_file:
pickle.dump(student_data, pickle_file)
print("\nStudent data serialized and saved to student_data.pkl.")
# Deserialize the dictionary from the pickle file
with open('student_data.pkl', 'rb') as pickle_file:
loaded_data = pickle.load(pickle_file)
print("Deserialized student data:")
print(loaded_data)
except FileNotFoundError as e:
print(f"Error: The pickle file does not exist. {e}")
except IOError as e:
print(f"Error reading or writing pickle file: {e}")
except pickle.UnpicklingError as e:
print(f"Error during unpickling: {e}")
OUTPUT:
4. Create a GUI-based student management system using Tkinter (or any GUI toolkit
of your choice) that performs CRUD operations on a database (SQLite/MySQL). The
system should include:
• A form with entry fields for Student ID, Name, Age, and Marks.
• Buttons for adding, updating, deleting, and displaying student records.
• A listbox or text area to display student records.
• A database connection where records are stored and retrieved from SQLite/MySQL.
• Proper validation (e.g., preventing empty fields, ensuring marks are numeric).
PROGRAM:
import sqlite3
import tkinter as tk
from tkinter import messagebox
from tkinter import ttk
def init_db():
conn = sqlite3.connect("students.db")
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER NOT NULL,
marks REAL NOT NULL
)
""")
conn.commit()
conn.close()
def add_student():
if not (entry_id.get() and entry_name.get() and
entry_age.get() and entry_marks.get()):
messagebox.showerror("Error", "All fields
are required!")
return
try:
conn = sqlite3.connect("students.db")
cursor = conn.cursor()
cursor.execute("INSERT INTO students
VALUES (?, ?, ?, ?)",
(entry_id.get(), entry_name.get(),
int(entry_age.get()), float(entry_marks.get())))
conn.commit()
conn.close()
messagebox.showinfo("Success", "Student
added successfully!")
display_students()
except Exception as e:
messagebox.showerror("Error", str(e))
def update_student():
try:
conn = sqlite3.connect("students.db")
cursor = conn.cursor()
cursor.execute("UPDATE students SET
name=?, age=?, marks=? WHERE id=?",
(entry_name.get(), int(entry_age.get()),
float(entry_marks.get()), entry_id.get()))
conn.commit()
conn.close()
messagebox.showinfo("Success", "Student
updated successfully!")
display_students()
except Exception as e:
messagebox.showerror("Error", str(e))
def delete_student():
try:
conn = sqlite3.connect("students.db")
cursor = conn.cursor()
cursor.execute("DELETE FROM students
WHERE id=?", (entry_id.get(),))
conn.commit()
conn.close()
messagebox.showinfo("Success", "Student
deleted successfully!")
display_students()
except Exception as e:
messagebox.showerror("Error", str(e))
def display_students():
conn = sqlite3.connect("students.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM students")
records = cursor.fetchall()
conn.close()
tree.delete(*tree.get_children())
for record in records:
tree.insert("", tk.END, values=record)
init_db()
root = tk.Tk()
root.title("Student Management System")
root.geometry("600x450")
root.configure(bg="#e6f7ff")
style = ttk.Style()
style.configure("TButton", font=("Arial", 10,
"bold"), padding=6, background="#0073e6",
foreground="black")
style.configure("TLabel", font=("Arial", 10,
"bold"), background="#e6f7ff")
style.configure("Treeview", font=("Arial", 10))
style.configure("Treeview.Heading",
font=("Arial", 10, "bold"))
tk.Label(root, text="Student ID:", bg="#e6f7ff",
font=("Arial", 10, "bold")).grid(row=0,
column=0, padx=10, pady=5)
tk.Label(root, text="Name:", bg="#e6f7ff",
font=("Arial", 10, "bold")).grid(row=1,
column=0, padx=10, pady=5)
tk.Label(root, text="Age:", bg="#e6f7ff",
font=("Arial", 10, "bold")).grid(row=2,
column=0, padx=10, pady=5)
tk.Label(root, text="Marks:", bg="#e6f7ff",
font=("Arial", 10, "bold")).grid(row=3,
column=0, padx=10, pady=5)
entry_id = ttk.Entry(root)
entry_name = ttk.Entry(root)
entry_age = ttk.Entry(root)
entry_marks = ttk.Entry(root)
entry_id.grid(row=0, column=1, padx=10,
pady=5)
entry_name.grid(row=1, column=1, padx=10,
pady=5)
entry_age.grid(row=2, column=1, padx=10,
pady=5)
entry_marks.grid(row=3, column=1, padx=10,
pady=5)
btn_frame = tk.Frame(root, bg="#e6f7ff")
btn_frame.grid(row=4, column=0,
columnspan=2, pady=10)
ttk.Button(btn_frame, text="Add",
command=add_student).grid(row=0, column=0,
padx=10, pady=5)
ttk.Button(btn_frame, text="Update",
command=update_student).grid(row=0,
column=1, padx=10, pady=5)
ttk.Button(btn_frame, text="Delete",
command=delete_student).grid(row=0,
column=2, padx=10, pady=5)
ttk.Button(btn_frame, text="Display",
command=display_students).grid(row=0,
column=3, padx=10, pady=5)
tree = ttk.Treeview(root, columns=("ID",
"Name", "Age", "Marks"), show="headings")
tree.heading("ID", text="ID")
tree.heading("Name", text="Name")
tree.heading("Age", text="Age")
tree.heading("Marks", text="Marks")
tree.column("ID", width=50)
tree.column("Name", width=150)
tree.column("Age", width=50)
tree.column("Marks", width=70)
tree.grid(row=5, column=0, columnspan=2,
padx=10, pady=10)
display_students()
root.mainloop()
OUTPUT:
UPDATE:
DELETE:
5. Write a Python program that:
• Uses NumPy and SciPy to solve a system of linear equations (e.g., Ax = B).
• Computes the determinant, inverse, and eigenvalues of a given matrix.
PROGRAM:
import numpy as np
from scipy.linalg import solve, det, inv, eig
# Define matrix A and vector B for Ax = B
A = np.array([[3, 2, -1],
[2, -2, 4],
[-1, 0.5, -1]])
B = np.array([1, -2, 0])
# Solve Ax = B
x = solve(A, B)
x_int = np.round(x).astype(int) # Convert to integers
print("Solution of Ax = B:", x_int)
# Compute determinant
determinant = round(det(A)) # Round to nearest integer
print("Determinant of A:", determinant)
# Compute inverse
if determinant != 0:
inverse_A = inv(A)
inverse_A_int = np.round(inverse_A).astype(int) # Convert to integers
print("Inverse of A:\n", inverse_A_int)
else:
print("Matrix A is singular, no inverse exists.")
# Compute eigenvalues
eigenvalues, eigenvectors = eig(A)
eigenvalues_int = np.round(eigenvalues).astype(int) # Convert to integers
eigenvectors_int = np.round(eigenvectors).astype(int) # Convert to integers
print("Eigenvalues of A:", eigenvalues_int)
print("Eigenvectors of A:\n", eigenvectors_int)
OUTPUT: