0% found this document useful (0 votes)
51 views37 pages

Advanced Python Programming Exam

Uploaded by

sanketabhang0
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)
51 views37 pages

Advanced Python Programming Exam

Uploaded by

sanketabhang0
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/ 37

1a) Write a python program to demonstrate creating a class, defining attributes and methods.

# Define the Student class

class Student:

def __init__(self, name, age, grade):

self.name = name

self.age = age

self.grade = grade

def display_details(self):

print(f"Name: {self.name}, Age: {self.age}, Grade: {self.grade}")

def has_passed(self):

if self.grade >= 50:

print(f"{self.name} has passed.")

else:

print(f"{self.name} has not passed.")

# Dictionary to store students

students = {

"Alice": Student("Alice", 20, 85),

"Alen": Student("Alen", 19, 72),

"Bob": Student("Bob", 22, 45),

"Sam": Student("Sam", 20, 42),

"Charlie": Student("Charlie", 19, 60),

"Dan": Student("Dan", 19, 70),

}
# Interactive prompt

while True:

name = input("Enter the name of the student (or type 'exit' to quit): ")

if name.lower() == 'exit':

print("Exiting the program.")

break

if name in students:

student = students[name]

student.display_details()

student.has_passed()

else:

print(f"No student found with the name '{name}'.")

1b) Implement a program to showcase constructor and destructor.

# Define the Book class

class Book:

def __init__(self, title, author):

self.title = title

self.author = author

print(f"Book '{self.title}' by {self.author} is created.")

def __del__(self):

print(f"Book '{self.title}' is deleted.")


def display_details(self):

print(f"Title: {self.title}, Author: {self.author}")

# Dictionary to store books

books = {

"1984": Book("1984", "George Orwell"),

"To Kill a Mockingbird": Book("To Kill a Mockingbird", "Harper Lee"),

"The Great Gatsby": Book("The Great Gatsby", "F. Scott Fitzgerald"),

"Pride and Prejudice": Book("Pride and Prejudice", "Jane Austen")

# Interactive menu

while True:

print("\nOptions:")

print("1. View book details")

print("2. Add a book")

print("3. Delete a book")

print("4. Exit")

choice = input("Enter your choice (1/2/3/4): ")

if choice == "1":

title = input("Enter the title of the book: ").strip()

if title in books:

books[title].display_details()

else:
print(f"No book found with the title '{title}'.")

elif choice == "2":

title = input("Enter the title of the new book: ").strip()

author = input("Enter the author of the new book: ").strip()

if title not in books:

books[title] = Book(title, author)

print(f"Book '{title}' by {author} added successfully.")

else:

print(f"A book with the title '{title}' already exists.")

elif choice == "3":

title = input("Enter the title of the book to delete: ").strip()

if title in books:

del books[title]

else:

print(f"No book found with the title '{title}'.")

elif choice == "4":

print("Exiting the program.")

break

else:

print("Invalid choice. Please try again.")


2a) Create a python program to demonstrate the use of class variables, instance variables and
methods.

class Student:

# Class variable

school_name = "Springfield Elementary"

def __init__(self, name, age):

# Instance variables

self.name = name

self.age = age

# Instance method

def display_info(self):

print(f"Name: {self.name}, Age: {self.age}, School: {Student.school_name}")

# Create objects

student1 = Student("John", 15)

student2 = Student("Emma", 14)

# Display student information

student1.display_info()

student2.display_info()

# Modify class variable

Student.school_name = "Universal High School"


# Display again to see updated class variable

student1.display_info()

student2.display_info()

2b) Write a program that passes objects of one class as an argument to another class.

# Define Employee class

class Employee:

def __init__(self, name, salary):

self.name = name

self.salary = salary

def display(self):

print(f"Employee Name: {self.name}, Salary: {self.salary}")

# Define Department class

class Department:

def __init__(self, dept_name):

self.dept_name = dept_name

def show_department(self, emp):

print(f"{emp.name} works in {self.dept_name} Department with a Salary of {emp.salary}")

# Create Employee object

employee1 = Employee("Alice", 50000)

# Create Department object

department1 = Department("Human Resources")


# Call method with employee object as argument

department1.show_department(employee1)

3b) Write a program to demonstrate method overriding using a base and derived class

# Define base class

class Parent:

def show(self):

print("This is a parent class method.")

# Define derived class

class Child(Parent):

def show(self):

print("This is the child class method overriding parent's method.")

# Create objects

parent_obj = Parent()

child_obj = Child()

# Call methods

parent_obj.show() # Calls method from Parent

child_obj.show() # Calls overridden method from Child

3C)Implement operator overloading for a Python class (e.g., add two objects using + operator).

# Define ComplexNumber class

class ComplexNumber:

def __init__(self, real, imag):


self.real = real

self.imag = imag

# Overload + operator

def __add__(self, other):

return ComplexNumber(self.real + other.real, self.imag + other.imag)

# Overload - operator

def __sub__(self, other):

return ComplexNumber(self.real - other.real, self.imag - other.imag)

# Overload * operator

def __mul__(self, other):

real_part = self.real * other.real - self.imag * other.imag

imag_part = self.real * other.imag + self.imag * other.real

return ComplexNumber(real_part, imag_part)

def __str__(self):

return f"{self.real} + {self.imag}i"

# Create multiple complex number objects

num1 = ComplexNumber(3, 4)

num2 = ComplexNumber(1, 2)

num3 = ComplexNumber(5, 6)

num4 = ComplexNumber(2, 3)
# Perform addition

sum_result = num1 + num2 + num3 + num4

# Perform subtraction

sub_result = num1 - num2 - num3 - num4

# Perform multiplication

mul_result = num1 * num2 * num3 * num4

# Print the results

print("Sum of Complex Numbers:", sum_result)

print("Subtraction of Complex Numbers:", sub_result)

print("Multiplication of Complex Numbers:", mul_result)

4)Write a Python program to create an abstract class and implement it in


derived class
from abc import ABC, abstractmethod

# Define abstract class

class Shape(ABC):

@abstractmethod

def area(self):

"""Abstract method to calculate area"""

pass
@abstractmethod

def perimeter(self):

"""Abstract method to calculate perimeter"""

pass

# Rectangle class inherits from Shape

class Rectangle(Shape):

def __init__(self, length, width):

self.length = length

self.width = width

def area(self):

return self.length * self.width

def perimeter(self):

return 2 * (self.length + self.width)

# Circle class inherits from Shape

class Circle(Shape):

def __init__(self, radius):

self.radius = radius

def area(self):
return 3.14 * self.radius ** 2

def perimeter(self):

return 2 * 3.14 * self.radius

# Demonstration

rect = Rectangle(5, 3) # Create a Rectangle object

circle = Circle(4) # Create a Circle object

# Print the area and perimeter of the rectangle

print("Rectangle Area:", rect.area())

print("Rectangle Perimeter:", rect.perimeter())

# Print the area and perimeter of the circle

print("Circle Area:", circle.area())

print("Circle Perimeter:", circle.perimeter())

5a) Write a program to create multiple threads to demonstrate single-


tasking and multi-tasking.
import threading

import time
# Function for single tasking (one task per thread)

def single_task(task_name, delay):

print(f"Starting single task: {task_name}")

time.sleep(delay) # Simulate task processing

print(f"Single task completed: {task_name}")

# Function for multi-tasking (multiple threads running concurrently)

def multi_task(task_name, steps, delay):

print(f"Starting multi task: {task_name}")

for step in range(1, steps + 1):

print(f"{task_name}: Step {step}")

time.sleep(delay) # Simulate step processing

print(f"Multi task completed: {task_name}")

# Single Tasking Demonstration

print("\n-- Single Tasking Demonstration --")

# Create a single thread for one task

single_thread = threading.Thread(target=single_task, args=("Single Task 1", 2))

single_thread.start()

single_thread.join()

print("Single tasking completed.\n")


# Multi Tasking Demonstration

print("-- Multi Tasking Demonstration --")

# Create multiple threads for concurrent tasks

multi_thread1 = threading.Thread(target=multi_task, args=("Multi Task 1", 5, 1))

multi_thread2 = threading.Thread(target=multi_task, args=("Multi Task 2", 5, 1))

# Start the threads

multi_thread1.start()

multi_thread2.start()

# Wait for both threads to complete

multi_thread1.join()

multi_thread2.join()

print("Multi tasking completed.")

6b) Create a Python program to insert, update, and delete records


from a MySQL table.

import mysql.connector

try:
# Step 1: Establish the connection

connection = mysql.connector.connect(

host="localhost",

user="root",

password="Ayush2525",

database="School"

if connection.is_connected():

print("Connected to the MySQL database successfully!")

# Step 2: Create a cursor object

cursor = connection.cursor()

# Step 3: Check if 'students' table exists

cursor.execute("SHOW TABLES LIKE 'students'")

result = cursor.fetchone()

if not result:

print("Error: The table 'students' does not exist.")

else:

# INSERT a new record

insert_query = "INSERT INTO students (name, age, grade) VALUES (%s, %s, %s)"

data = ("Ravi", 16, 85)


cursor.execute(insert_query, data)

connection.commit()

print("Record inserted successfully!")

# UPDATE a record

update_query = "UPDATE students SET grade = %s WHERE name = %s"

data = (90, "Ravi")

cursor.execute(update_query, data)

connection.commit()

print("Record updated successfully!")

# DELETE a record

delete_query = "DELETE FROM students WHERE name = %s"

data = ("Ravi",)

cursor.execute(delete_query, data)

connection.commit()

print("Record deleted successfully!")

# SELECT all records

cursor.execute("SELECT * FROM students")

records = cursor.fetchall()

if records:

print("\nRetrieved Records:")

for row in records:


print(row)

else:

print("No records found in the 'students' table!")

except mysql.connector.Error as err:

print(f"Error: {err}")

finally:

# Close cursor and connection

if 'cursor' in locals():

cursor.close()

if 'connection' in locals() and connection.is_connected():

connection.close()

print("Database connection closed.")

6c) Write a program to create a new database table using Python.


import mysql.connector

try:

# Step 1: Connect to MySQL Server (without selecting a database yet)

connection = mysql.connector.connect(

host="localhost",

user="root",
password="Ayush2525"

if connection.is_connected():

print("Connected to MySQL Server successfully!")

# Step 2: Create a cursor

cursor = connection.cursor()

# Step 3: Create the database if it doesn't exist

cursor.execute("CREATE DATABASE IF NOT EXISTS School")

print("Database 'School' checked/created.")

# Step 4: Select the database

cursor.execute("USE School")

# Step 5: Create the table

create_table_query = """

CREATE TABLE IF NOT EXISTS students (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100) NOT NULL,

age INT,
grade FLOAT

"""

cursor.execute(create_table_query)

print("Table 'students' created successfully!")

except mysql.connector.Error as err:

print(f"Error: {err}")

finally:

# Step 6: Close the connection

if 'cursor' in locals():

cursor.close()

if 'connection' in locals() and connection.is_connected():

connection.close()

print("Database connection closed.")

7a) Write a Python program to handle exceptions using try-


except-else-finally.
import mysql.connector
try:

# Connect to the database

conn = mysql.connector.connect(

host="localhost",

user="root",

password="root@123",

database="mydatabase"

cursor = conn.cursor()

print("Connected to the database successfully!")

# Fetch and display existing student records

cursor.execute("SELECT * FROM students")

students = cursor.fetchall()

if students:

print("\nExisting Students:")

for student in students:


print(f"ID: {student[0]}, Name: {student[1]}, Marks: {student[2]},
Status: {student[3]}")

else:

print("\nNo student records found.")

# Ask if user wants to add a new student

add_student = input("\nDo you want to add a new student? (yes/no):


").strip().lower()

if add_student == "yes":

name = input("Enter student name: ").strip()

try:

marks = int(input("Enter marks (0-100): "))

if marks < 0 or marks > 100:

raise ValueError("Marks should be between 0 and 100!")

# Determine status

status = "pass" if marks >= 40 else "fail"


except ValueError as ve:

print(f"Invalid input: {ve}")

else:

# Insert the new student

insert_query = "INSERT INTO students (name, marks, status)


VALUES (%s, %s, %s)"

cursor.execute(insert_query, (name, marks, status))

conn.commit()

print(f"\nStudent '{name}' added successfully with marks


{marks}, Status: {status}")

except mysql.connector.Error as sql_error:

print(f"Database error: {sql_error}")

finally:

# Always close connection

if 'cursor' in locals():

cursor.close()

if 'conn' in locals() and conn.is_connected():


conn.close()

print("Connection closed.")

7b) Create a user-defined exception class and


demonstrate its use in a program
import mysql.connector

# Custom Exception for Invalid Employee Data


class EmployeeDataError(Exception):
def __init__(self, message="Employee data is invalid!"):
self.message = message
super().__init__(self.message)

try:
# Connect to MySQL Database
conn = mysql.connector.connect(
host="localhost",
user="root",
password="Penil123456@#$%",
database="company"
)
cursor = conn.cursor()
print("Connected to database successfully!\n")

# Fetch existing employees


cursor.execute("SELECT * FROM employees")
employees = cursor.fetchall()

print("Existing Employees:")
for emp in employees:
print(f"ID: {emp[0]}, Name: {emp[1]}, Age: {emp[2]}, Salary:
₹{emp[3]}, Department: {emp[4]}")

add_employee = input("\nDo you want to add a new


employee? (yes/no): ").strip().lower()

if add_employee == "yes":
name = input("Enter employee name: ").strip()
try:
age = int(input("Enter age (18-60): "))
salary = float(input("Enter salary (Minimum ₹10,000): "))
department = input("Enter department: ").strip()

if age < 18 or age > 60:


raise EmployeeDataError("Age must be between 18
and 60!")

if salary < 10000:


raise EmployeeDataError("Salary must be at least
₹10,000!")

# Insert into database


cursor.execute(
"INSERT INTO employees (name, age, salary,
department) VALUES (%s, %s, %s, %s)",
(name, age, salary, department)
)
conn.commit()
print(f"\nEmployee '{name}' added successfully!")

except ValueError:
print("Invalid input! Age must be a number, and salary
must be a valid amount.")
except EmployeeDataError as e:
print(f"Employee data error: {e}")

except mysql.connector.Error as sql_error:


print(f"Database error: {sql_error}")

finally:
if 'cursor' in locals():
cursor.close()
if 'conn' in locals() and conn.is_connected():
conn.close()
print("Connection closed.")
#SQL Code
CREATE DATABASE company;
USE company;

CREATE TABLE employees (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
age INT NOT NULL CHECK (age BETWEEN 18 AND 60),
salary DECIMAL(10, 2) NOT NULL CHECK (salary >= 10000),
department VARCHAR(50) NOT NULL
);

-- Sample data
INSERT INTO employees (name, age, salary, department)
VALUES
('John Doe', 30, 50000, 'IT'),
('Jane Smith', 45, 70000, 'HR'),
('Alice Johnson', 22, 25000, 'Marketing');

8)Write a Python program to implement a multi-client


chat system using socket programming and multi-
threading.

import socket
import threading

HOST = '127.0.0.1'
PORT = 5555

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


server.bind((HOST, PORT))
server.listen()

clients = []
print("Server is running and waiting for connections...")

def handle_client(client, addr):


while True:
try:
message = client.recv(1024).decode('utf-8')
if not message:
break
print(f"Client {addr}: {message}")
reply = f"Server: I received your message -> {message}"
client.send(reply.encode('utf-8'))
except:
print(f"Client {addr} disconnected.")
if client in clients:
clients.remove(client)
client.close()
break
def receive_connections():
while True:
client, addr = server.accept()
print(f"Connected with {addr}")
clients.append(client)
thread = threading.Thread(target=handle_client,
args=(client, addr))
thread.start()

def send_messages():
while True:
message = input("Server: ")
for client in clients[:]:
try:
client.send(f"Server: {message}".encode('utf-8'))
except:
clients.remove(client)
threading.Thread(target=receive_connections).start()
threading.Thread(target=send_messages).start()

#client Code
import socket
import threading

HOST = '127.0.0.1'
PORT = 5555

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


client.connect((HOST, PORT))

print("Connected to the server. Type your message:")

def receive_messages():
while True:
try:
message = client.recv(1024).decode('utf-8')
if not message:
break
print(message)
except:
print("Disconnected from server.")
client.close()
break

# Start thread to receive messages


threading.Thread(target=receive_messages,
daemon=True).start()

# Send messages
while True:
message = input("You: ")
if message.lower() == "exit":
print("Closing connection...")
client.close()
break
client.send(message.encode('utf-8'))

9)Develop a simple banking system using Tkinter for


GUI and SQLite for database storage.
import sqlite3

import tkinter as tk

from tkinter import messagebox

# Connect to SQLite database

conn = sqlite3.connect("bank.db")

cursor = conn.cursor()

# Create table if it doesn't exist

cursor.execute("CREATE TABLE IF NOT EXISTS accounts (name TEXT


PRIMARY KEY, balance REAL)")

conn.commit()

# Function to create a new account


def create_account():

name = name_entry.get()

if name == "":

messagebox.showerror("Error", "Name cannot be empty!")

return

try:

cursor.execute("INSERT INTO accounts (name, balance) VALUES


(?, ?)", (name, 0))

conn.commit()

messagebox.showinfo("Success", "Account Created!")

except sqlite3.IntegrityError:

messagebox.showerror("Error", "Account already exists!")

# Function to deposit amount

def deposit():

name = name_entry.get()

try:

amount = float(amount_entry.get())

cursor.execute("UPDATE accounts SET balance = balance + ?


WHERE name = ?", (amount, name))
if cursor.rowcount == 0:

messagebox.showerror("Error", "Account not found!")

else:

conn.commit()

messagebox.showinfo("Success", "Amount Deposited!")

except ValueError:

messagebox.showerror("Error", "Please enter a valid amount!")

# Function to check balance

def check_balance():

name = name_entry.get()

cursor.execute("SELECT balance FROM accounts WHERE name = ?",


(name,))

balance = cursor.fetchone()

if balance:

messagebox.showinfo("Balance", f"Current Balance: ₹


{balance[0]:.2f}")

else:

messagebox.showerror("Error", "Account not found!")


# GUI Setup

root = tk.Tk()

root.title("Bank System")

tk.Label(root, text="Name:").pack()

name_entry = tk.Entry(root)

name_entry.pack()

tk.Label(root, text="Amount:").pack()

amount_entry = tk.Entry(root)

amount_entry.pack()

tk.Button(root, text="Create Account",


command=create_account).pack(pady=2)

tk.Button(root, text="Deposit", command=deposit).pack(pady=2)

tk.Button(root, text="Check Balance",


command=check_balance).pack(pady=2)

root.mainloop()
10)Write a Python program to analyze student marks
using Pandas and visualize data with Matplotlib
import pandas as pd

import matplotlib.pyplot as plt

# Data to be used in the DataFrame

data = {

"Student": ["Alice", "Bob", "Charlie", "David"],

"Marks": [85, 90, 78, 88]

# Creating DataFrame from data

df = pd.DataFrame(data)

# Displaying the DataFrame

print("Student Marks Data:\n", df)


# Plotting the bar chart

plt.bar(df["Student"], df["Marks"], color=['blue', 'green', 'red', 'purple'])

# Adding labels and title to the chart

plt.xlabel("Students")

plt.ylabel("Marks")

plt.title("Student Performance")

# Display the chart

plt.show()

You might also like