0% found this document useful (0 votes)
3 views12 pages

Complted Python Assignment Two

The document contains multiple Python programming assignments covering multi-threading, exception handling, file operations, a GUI-based student management system, and solving linear equations using NumPy and SciPy. Each section includes code examples demonstrating the required functionalities such as thread synchronization, error handling, CRUD operations with a database, and matrix computations. The assignments emphasize practical applications of Python programming concepts and libraries.

Uploaded by

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

Complted Python Assignment Two

The document contains multiple Python programming assignments covering multi-threading, exception handling, file operations, a GUI-based student management system, and solving linear equations using NumPy and SciPy. Each section includes code examples demonstrating the required functionalities such as thread synchronization, error handling, CRUD operations with a database, and matrix computations. The assignments emphasize practical applications of Python programming concepts and libraries.

Uploaded by

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

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

def print_numbers(event):
for i in range(1, 11):
print(i)
time.sleep(1)
event.set()

def print_letters(event):
for i in range(10):
print(chr(65 + i))
time.sleep(1)
event.set()

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

thread_numbers.start()
thread_letters.start()

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

def divide_numbers():
try:
num1 = input("Enter the numerator: ")
num2 = input("Enter the denominator: ")

assert num1.isdigit(), "Numerator must be a number!"


assert num2.isdigit(), "Denominator must be a number!"

num1 = int(num1)
num2 = int(num2)

assert num1 >= 0, "Numerator must be a positive number!"


assert num2 > 0, "Denominator must be a positive number!"

if num1 < 0 or num2 < 0:


raise NegativeNumberError("Input number cannot be negative.")

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 = {
'Student1': {'name': 'Diksha', 'age': 19, 'marks': 90},
'Student2': {'name': 'Aditi', 'age': 19, 'marks': 90},
}

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

try:
with open('student_data.txt', 'r') as file:
content = file.read()
print("\nContents of student_data.txt using read():")
print(content)

file.seek(0)
print("\nContents of student_data.txt using readline():")
print(file.readline())

file.seek(0)
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}")

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

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

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

A = np.array([[3, 2, -1],
[2, -2, 4],
[-1, 0.5, -1]])
B = np.array([1, -2, 0])

x = solve(A, B)
x_int = np.round(x).astype(int)
print("Solution of Ax = B:", x_int)

determinant = round(det(A))
print("Determinant of A:", determinant)

if determinant != 0:
inverse_A = inv(A)
inverse_A_int = np.round(inverse_A).astype(int)
print("Inverse of A:\n", inverse_A_int)
else:
print("Matrix A is singular, no inverse exists.")

eigenvalues, eigenvectors = eig(A)


eigenvalues_int = np.round(eigenvalues).astype(int)
eigenvectors_int = np.round(eigenvectors).astype(int)
print("Eigenvalues of A:", eigenvalues_int)
print("Eigenvectors of A:\n", eigenvectors_int)
Let me know if you need any modifications.

OUTPUT:

You might also like