Assignment
Assignment
Source Code:
import threading
import time
def print_numbers():
for i in range(1, 11):
print(i)
time.sleep(1)
def print_letters():
for letter in range(ord('A'), ord('J') + 1):
print(chr(letter))
time.sleep(1)
if __name__ == "__main__":
try:
# Creating threads
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
# Starting threads
thread1.start()
thread2.start()
except RuntimeError as e:
print(f"Error: {e}. Ensure system resources allow thread creation.")
Output:
Source-code
class NegativeNumberError(Exception):
"""Custom exception for negative numbers."""
pass
def divide_numbers():
try:
# Taking user input
num1 = float(input("Enter numerator: "))
num2 = float(input("Enter denominator: "))
# Performing division
result = num1 / num2
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Invalid input. Please enter numeric values.")
except NegativeNumberError as e:
print(f"Error: {e}")
except AssertionError as e:
print(f"AssertionError: {e}")
finally:
print("Execution completed.")
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.
Source-Code:
import os
import pickle
# Function to read and display file contents using different read methods
def read_student_data():
try:
with open("student_data.txt", "r") as file:
print("\nReading entire file using read():")
print(file.read())
with open("student_data.txt", "r") as file:
print("\nReading line by line using readline():")
print(file.readline().strip()) # Reads first line
print(file.readline().strip()) # Reads second line
except FileNotFoundError:
print("Error: student_data.txt not found.")
except IOError as e:
print(f"Error reading file: {e}")
os.remove("student_records.txt")
print("File student_records.txt deleted successfully.")
except FileNotFoundError:
print("Error: File not found for renaming or deletion.")
except PermissionError:
print("Error: Permission denied while renaming or deleting the file.")
except IOError as e:
print(f"File operation error: {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).
SOURCE-CODE
import sqlite3
import tkinter as tk
from tkinter import messagebox
# Database Connection
conn = sqlite3.connect("students.db")
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
student_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER NOT NULL,
marks REAL NOT NULL
)
""")
conn.commit()
# GUI Application
class StudentManagementApp:
def __init__(self, root):
self.root = root
self.root.title("Student Management System")
self.root.geometry("500x500")
self.student_id = tk.Entry(root)
self.name = tk.Entry(root)
self.age = tk.Entry(root)
self.marks = tk.Entry(root)
# Buttons
tk.Button(root, text="Add", command=self.add_student).grid(row=4, column=0, pady=10)
tk.Button(root, text="Update", command=self.update_student).grid(row=4, column=1,
pady=10)
tk.Button(root, text="Delete", command=self.delete_student).grid(row=5, column=0,
pady=10)
tk.Button(root, text="Display", command=self.display_students).grid(row=5, column=1,
pady=10)
def validate_input(self):
"""Validates input fields before performing operations."""
if not self.student_id.get() or not self.name.get() or not self.age.get() or not self.marks.get():
messagebox.showerror("Error", "All fields must be filled!")
return False
if not self.age.get().isdigit() or not self.marks.get().replace('.', '', 1).isdigit():
messagebox.showerror("Error", "Age and Marks must be numeric!")
return False
return True
def add_student(self):
"""Adds a new student record to the database."""
if not self.validate_input():
return
try:
cursor.execute("INSERT INTO students (student_id, name, age, marks) VALUES
(?, ?, ?, ?)",
(self.student_id.get(), self.name.get(), int(self.age.get()), float(self.marks.get())))
conn.commit()
messagebox.showinfo("Success", "Student added successfully!")
self.clear_fields()
except sqlite3.IntegrityError:
messagebox.showerror("Error", "Student ID already exists!")
def update_student(self):
"""Updates an existing student record."""
if not self.validate_input():
return
def delete_student(self):
"""Deletes a student record based on Student ID."""
if not self.student_id.get():
messagebox.showerror("Error", "Enter Student ID to delete!")
return
def display_students(self):
"""Displays all student records in the listbox."""
self.listbox.delete(0, tk.END)
cursor.execute("SELECT * FROM students")
records = cursor.fetchall()
for record in records:
self.listbox.insert(tk.END, record)
def clear_fields(self):
"""Clears all input fields."""
self.student_id.delete(0, tk.END)
self.name.delete(0, tk.END)
self.age.delete(0, tk.END)
self.marks.delete(0, tk.END)
OUTPUT:
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.
SOURCE-CODE:
import numpy as np
from scipy.linalg import solve
def solve_linear_system():
"""Solves a system of linear equations Ax = B using SciPy."""
A = np.array([[2, 1], [1, -1]]) # Coefficient matrix
B = np.array([3, 0]) # Constant matrix
try:
X = solve(A, B) # Solving for x
print("Solution to Ax = B:", X)
except np.linalg.LinAlgError as e:
print("Error solving the system:", e)
def matrix_operations():
"""Computes determinant, inverse, and eigenvalues of a matrix."""
M = np.array([[5, 2], [4, 1]]) # Example matrix
# Determinant
det = np.linalg.det(M)
print("\nDeterminant of M:", det)
# Eigenvalues
eigenvalues, eigenvectors = np.linalg.eig(M)
print("Eigenvalues of M:", eigenvalues)
print("Eigenvectors of M:\n", eigenvectors)
# Run the functions
solve_linear_system()
matrix_operations()
OUTPUT: