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

Adit Python Assignment 2

The document contains multiple Python programming assignments focusing on various concepts such as multi-threading, exception handling, file operations, GUI development, and numerical computations. Key tasks include implementing threads to print numbers and letters, handling exceptions during division, managing student records in a file and database, and solving linear equations using NumPy and SciPy. Each section includes code examples demonstrating the required functionality.

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 DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views12 pages

Adit Python Assignment 2

The document contains multiple Python programming assignments focusing on various concepts such as multi-threading, exception handling, file operations, GUI development, and numerical computations. Key tasks include implementing threads to print numbers and letters, handling exceptions during division, managing student records in a file and database, and solving linear equations using NumPy and SciPy. Each section includes code examples demonstrating the required functionality.

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 DOCX, 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
# 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 tkinter as tk from tkinter
import messagebox
import sqlite3

# Create a SQLite database or connect to one conn


= sqlite3.connect('student_management.db')
cursor = conn.cursor()

# Create table if it doesn't exist


cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
student_id INTEGER PRIMARY KEY,
name TEXT NOT NULL, age INTEGER
NOT NULL,
marks INTEGER NOT NULL
)
''')
conn.commit()

# Function to add a student record


def add_student(): student_id =
entry_student_id.get() name =
entry_name.get() age =
entry_age.get()
marks = entry_marks.get()

# Validate fields if not student_id or not name or


not age or not marks:
messagebox.showwarning("Input Error", "Please fill in all fields.")
return

try:
student_id = int(student_id)
age = int(age)
marks = int(marks) #
Insert into database
cursor.execute('''
INSERT INTO students (student_id, name, age, marks)
VALUES (?, ?, ?, ?)
''', (student_id, name, age, marks))
conn.commit()

messagebox.showinfo("Success", "Student added successfully.")


display_students()
clear_fields()

except ValueError:
messagebox.showwarning("Input Error", "Student ID, Age, and Marks must be numeric.")

# Function to update a student record


def update_student(): student_id =
entry_student_id.get() name =
entry_name.get() age =
entry_age.get()
marks = entry_marks.get()

if not student_id or not name or not age or not marks:


messagebox.showwarning("Input Error", "Please fill in all fields.") return

try:
student_id = int(student_id)
age = int(age)
marks = int(marks)

cursor.execute('''
UPDATE students
SET name = ?, age = ?, marks = ?
WHERE student_id = ?
''', (name, age, marks, student_id))
conn.commit()

messagebox.showinfo("Success", "Student updated successfully.")


display_students()
clear_fields()
except ValueError: messagebox.showwarning("Input Error", "Student ID, Age, and Marks
must be numeric.")
# Function to delete a student record
def delete_student(): student_id =
entry_student_id.get()

if not student_id:
messagebox.showwarning("Input Error", "Please enter a student ID.")
return

try:
student_id = int(student_id)

cursor.execute('''
DELETE FROM students WHERE student_id = ?
''', (student_id,))
conn.commit()

messagebox.showinfo("Success", "Student deleted successfully.")


display_students()
clear_fields()

except ValueError:
messagebox.showwarning("Input Error", "Student ID must be numeric.")

# Function to display all student records def


display_students():
listbox.delete(0, tk.END)

cursor.execute('SELECT * FROM students')


rows = cursor.fetchall()

for row in rows:


listbox.insert(tk.END, f"ID: {row[0]}, Name: {row[1]}, Age: {row[2]}, Marks: {row[3]}")

# Function to clear the input fields def


clear_fields():
entry_student_id.delete(0, tk.END)
entry_name.delete(0, tk.END)
entry_age.delete(0, tk.END)
entry_marks.delete(0, tk.END)

# Create the main window


root = tk.Tk()
root.title("Student Management System")

# Create the form labels and entry fields tk.Label(root,


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

entry_student_id = tk.Entry(root)
entry_name = tk.Entry(root) entry_age
= tk.Entry(root)
entry_marks = tk.Entry(root)

entry_student_id.grid(row=0, column=1)
entry_name.grid(row=1, column=1) entry_age.grid(row=2,
column=1)
entry_marks.grid(row=3, column=1)

# Create the buttons for operations btn_add = tk.Button(root, text="Add Student",


command=add_student) btn_update = tk.Button(root, text="Update Student",
command=update_student) btn_delete = tk.Button(root, text="Delete Student",
command=delete_student) btn_display = tk.Button(root, text="Display Students",
command=display_students) btn_clear = tk.Button(root, text="Clear Fields",
command=clear_fields)

btn_add.grid(row=4, column=0)
btn_update.grid(row=4, column=1)
btn_delete.grid(row=5, column=0)
btn_display.grid(row=5, column=1)
btn_clear.grid(row=6, column=0, columnspan=2)
listbox = tk.Listbox(root, width=50, height=10)
listbox.grid(row=7, column=0, columnspan=2)
root.mainloop() conn.close()
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:

You might also like