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

Assignment

The document contains multiple Python programming assignments that cover various topics including multi-threading, exception handling, file operations, GUI development, and linear algebra using NumPy and SciPy. Each assignment includes source code examples demonstrating the required functionalities such as thread synchronization, custom exception handling, file read/write operations, a student management GUI, and solving linear equations. The document serves as a comprehensive guide for implementing these programming concepts.

Uploaded by

priyanshayeole
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Assignment

The document contains multiple Python programming assignments that cover various topics including multi-threading, exception handling, file operations, GUI development, and linear algebra using NumPy and SciPy. Each assignment includes source code examples demonstrating the required functionalities such as thread synchronization, custom exception handling, file read/write operations, a student management GUI, and solving linear equations. The document serves as a comprehensive guide for implementing these programming concepts.

Uploaded by

priyanshayeole
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

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.

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()

# Ensuring both threads complete execution before exiting


thread1.join()
thread2.join()

print("Both threads have finished execution.")

except RuntimeError as e:
print(f"Error: {e}. Ensure system resources allow thread creation.")
Output:

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.

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: "))

# Checking for negative numbers


assert num1 >= 0 and num2 >= 0, "Inputs must be positive."
# Raising custom exception if negative
if num1 < 0 or num2 < 0:
raise NegativeNumberError("Negative numbers are not allowed.")

# 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.")

# Running the function


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.

Source-Code:

import os
import pickle

# Function to create and write student data into a text file


def write_student_data():
try:
with open("student_data.txt", "w") as file:
file.write("Name, Age, Marks\n")
file.write("Alice, 20, 85\n")
file.write("Bob, 22, 78\n")
file.write("Charlie, 21, 90\n")
print("Student data successfully written to student_data.txt.")
except IOError as e:
print(f"Error writing to file: {e}")

# 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

with open("student_data.txt", "r") as file:


print("\nReading all lines using readlines():")
for line in file.readlines():
print(line.strip())

except FileNotFoundError:
print("Error: student_data.txt not found.")
except IOError as e:
print(f"Error reading file: {e}")

# Function to rename and delete the file


def rename_and_delete_file():
try:
os.rename("student_data.txt", "student_records.txt")
print("\nFile renamed to student_records.txt.")

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}")

# Function to serialize and deserialize student data using pickle


def pickle_student_data():
student_dict = {
"Alice": {"Age": 20, "Marks": 85},
"Bob": {"Age": 22, "Marks": 78},
"Charlie": {"Age": 21, "Marks": 90}
}

# Serializing student data


try:
with open("student_data.pkl", "wb") as file:
pickle.dump(student_dict, file)
print("\nStudent data serialized and saved as student_data.pkl.")
except IOError as e:
print(f"Error serializing data: {e}")

# Deserializing student data


try:
with open("student_data.pkl", "rb") as file:
loaded_data = pickle.load(file)
print("\nDeserialized Student Data:")
for name, info in loaded_data.items():
print(f"{name}: Age {info['Age']}, Marks {info['Marks']}")
except FileNotFoundError:
print("Error: student_data.pkl not found for deserialization.")
except pickle.UnpicklingError:
print("Error: Corrupt data while deserializing.")

# Main function to execute all operations


if __name__ == "__main__":
write_student_data()
read_student_data()
rename_and_delete_file()
pickle_student_data()

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")

# Labels and Entry Fields


tk.Label(root, text="Student ID:").grid(row=0, column=0, padx=10, pady=5)
tk.Label(root, text="Name:").grid(row=1, column=0, padx=10, pady=5)
tk.Label(root, text="Age:").grid(row=2, column=0, padx=10, pady=5)
tk.Label(root, text="Marks:").grid(row=3, column=0, padx=10, pady=5)

self.student_id = tk.Entry(root)
self.name = tk.Entry(root)
self.age = tk.Entry(root)
self.marks = tk.Entry(root)

self.student_id.grid(row=0, column=1, padx=10, pady=5)


self.name.grid(row=1, column=1, padx=10, pady=5)
self.age.grid(row=2, column=1, padx=10, pady=5)
self.marks.grid(row=3, column=1, padx=10, pady=5)

# 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)

# Listbox for Displaying Data


self.listbox = tk.Listbox(root, width=50)
self.listbox.grid(row=6, column=0, columnspan=2, 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

cursor.execute("UPDATE students SET name=?, age=?, marks=? WHERE student_id=?",


(self.name.get(), int(self.age.get()), float(self.marks.get()), self.student_id.get()))
conn.commit()
if cursor.rowcount > 0:
messagebox.showinfo("Success", "Student updated successfully!")
else:
messagebox.showerror("Error", "Student ID not found!")
self.clear_fields()

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

cursor.execute("DELETE FROM students WHERE student_id=?", (self.student_id.get(),))


conn.commit()
if cursor.rowcount > 0:
messagebox.showinfo("Success", "Student deleted successfully!")
else:
messagebox.showerror("Error", "Student ID not found!")
self.clear_fields()

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)

# Running the Application


if __name__ == "__main__":
root = tk.Tk()
app = StudentManagementApp(root)
root.mainloop()

# Close DB connection when application exits


conn.close()

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)

# Inverse (if determinant is non-zero)


if det != 0:
inv = np.linalg.inv(M)
print("Inverse of M:\n", inv)
else:
print("Matrix is singular; inverse does not exist.")

# 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:

You might also like