Practical_2
SET A
1) Student Class Program:-
class Student:
def __init__(self, name, roll_number, marks):
[Link] = name
self.roll_number = roll_number
[Link] = marks
def display_details(self):
print("Name:", [Link])
print("Roll Number:", self.roll_number)
print("Marks:", [Link])
print("----------------------")
# Input for first student
name1 = input("Enter name of student 1: ")
roll1 = int(input("Enter roll number of student 1: "))
marks1 = float(input("Enter marks of student 1: "))
# Input for second student
name2 = input("Enter name of student 2: ")
roll2 = int(input("Enter roll number of student 2: "))
marks2 = float(input("Enter marks of student 2: "))
# Creating objects
student1 = Student(name1, roll1, marks1)
student2 = Student(name2, roll2, marks2)
# Display details
print("\nStudent Details")
student1.display_details()
student2.display_details()
2) Book Class Program:-
class Book:
def __init__(self, title, author, price):
[Link] = title
[Link] = author
[Link] = price
def show_book_info(self):
print("Title:", [Link])
print("Author:", [Link])
print("Price:", [Link])
# User input
title = input("Enter book title: ")
author = input("Enter author name: ")
price = float(input("Enter book price: "))
# Create object
book1 = Book(title, author, price)
# Display book info
print("\nBook Information")
book1.show_book_info()
3) Calculator Class Program:-
class Calculator:
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
def add(self):
print("Addition =", self.num1 + self.num2)
def subtract(self):
print("Subtraction =", self.num1 - self.num2)
def multiply(self):
print("Multiplication =", self.num1 * self.num2)
def divide(self):
if self.num2 != 0:
print("Division =", self.num1 / self.num2)
else:
print("Division by zero not allowed")
# User input
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# Create object
calc = Calculator(num1, num2)
# Demonstrate methods
[Link]()
[Link]()
[Link]()
[Link]()
SET B
1) Employee Management System (Inheritance):-
class Employee:
def __init__(self, name, emp_id):
[Link] = name
self.emp_id = emp_id
def show_details(self):
print("Name:", [Link])
print("Employee ID:", self.emp_id)
class Developer(Employee):
def role(self):
print("Role: Developer")
class Tester(Employee):
def role(self):
print("Role: Tester")
class Manager(Employee):
def role(self):
print("Role: Manager")
# Creating objects
d = Developer("Rahul", 101)
t = Tester("Priya", 102)
m = Manager("Amit", 103)
d.show_details()
[Link]()
t.show_details()
[Link]()
m.show_details()
[Link]()
2) ATM with Private PIN (Encapsulation):-
class ATM:
def __init__(self, pin):
self.__pin = pin # private variable
def validate_pin(self, entered_pin):
if entered_pin == self.__pin:
print("Access Granted")
else:
print("Access Denied")
# User input
pin = int(input("Set your ATM PIN: "))
atm = ATM(pin)
entered = int(input("Enter PIN: "))
atm.validate_pin(entered)
3) User → Customer & DeliveryPerson (Inheritance):-
class User:
def __init__(self, name):
[Link] = name
def display_user(self):
print("User Name:", [Link])
class Customer(User):
def order(self):
print("Customer placed an order")
class DeliveryPerson(User):
def deliver(self):
print("Delivery person delivers the order")
c = Customer("Rohan")
d = DeliveryPerson("Suresh")
c.display_user()
[Link]()
d.display_user()
[Link]()
4) University → College → Student (Multilevel Inheritance):-
class University:
def uni_name(self):
print("University: Pune University")
class College(University):
def college_name(self):
print("College: ABC College")
class Student(College):
def student_info(self):
print("Student: Siddheshwar")
s = Student()
s.uni_name()
s.college_name()
s.student_info()
SET C
1) Abstract Class + Destructor (Database System):-
from abc import ABC, abstractmethod
class Database(ABC):
@abstractmethod
def connect(self):
pass
def __del__(self):
print("Database connection closed")
class MyDatabase(Database):
def connect(self):
print("Database connected")
db = MyDatabase()
[Link]()
2) Method Overriding (Runtime Polymorphism):-
class Employee:
def calculate_salary(self):
print("Base salary calculation")
class Manager(Employee):
def calculate_salary(self):
print("Manager salary = 80000")
class Developer(Employee):
def calculate_salary(self):
print("Developer salary = 50000")
e1 = Manager()
e2 = Developer()
e1.calculate_salary()
e2.calculate_salary()
Assignment 3: Decorators
1) Person → Student using @property:-
class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
@property
def name(self):
return self.__name
@property
def age(self):
return self.__age
def display(self):
print("Name:", self.__name)
print("Age:", self.__age)
class Student(Person):
def __init__(self, name, age, roll_number, marks):
super().__init__(name, age)
self.__roll_number = roll_number
self.__marks = marks
@property
def roll_number(self):
return self.__roll_number
@property
def marks(self):
return self.__marks
def display_student(self):
[Link]()
print("Roll Number:", self.__roll_number)
print("Marks:", self.__marks)
# User input
name = input("Enter name: ")
age = int(input("Enter age: "))
roll = int(input("Enter roll number: "))
marks = float(input("Enter marks: "))
s = Student(name, age, roll, marks)
print("\nStudent Details")
s.display_student()
2) Vehicle → Car (Method Overriding):-
class Vehicle:
def start(self):
print("Starting vehicle")
class Car(Vehicle):
def start(self):
print("Starting car")
# user input just for demonstration
v = input("Press Enter to start vehicle...")
vehicle = Vehicle()
[Link]()
c = input("Press Enter to start car...")
car = Car()
[Link]()
3) Shape → Rectangle & Triangle (Polymorphism):-
class Shape:
def area(self):
pass
class Rectangle(Shape):
def __init__(self, length, width):
[Link] = length
[Link] = width
def area(self):
return [Link] * [Link]
class Triangle(Shape):
def __init__(self, base, height):
[Link] = base
[Link] = height
def area(self):
return 0.5 * [Link] * [Link]
# User input
l = float(input("Enter rectangle length: "))
w = float(input("Enter rectangle width: "))
b = float(input("Enter triangle base: "))
h = float(input("Enter triangle height: "))
r = Rectangle(l, w)
t = Triangle(b, h)
print("Rectangle Area =", [Link]())
print("Triangle Area =", [Link]())
SET B
1) Abstraction – Appliance Example:-
from abc import ABC, abstractmethod
class Appliance(ABC):
@abstractmethod
def operate(self):
pass
class WashingMachine(Appliance):
def operate(self):
print("Washing Machine is washing clothes")
class Microwave(Appliance):
def operate(self):
print("Microwave is heating food")
input("Press Enter to operate Washing Machine")
w = WashingMachine()
[Link]()
input("Press Enter to operate Microwave")
m = Microwave()
[Link]()
2) Multiple Inheritance + MRO:-
class Teacher:
def __init__(self, name, subject):
self.__name = name
self.__subject = subject
@property
def name(self):
return self.__name
@property
def subject(self):
return self.__subject
def display_info(self):
print("Teacher Name:", self.__name)
print("Subject:", self.__subject)
class Researcher:
def __init__(self, field, publications):
self.__field = field
self.__publications = publications
@property
def field(self):
return self.__field
@property
def publications(self):
return self.__publications
def display_info(self):
print("Research Field:", self.__field)
print("Publications:", self.__publications)
class Professor(Teacher, Researcher):
def __init__(self, name, subject, field, publications):
Teacher.__init__(self, name, subject)
Researcher.__init__(self, field, publications)
# User input
name = input("Enter name: ")
subject = input("Enter subject: ")
field = input("Enter research field: ")
pub = int(input("Enter number of publications: "))
p = Professor(name, subject, field, pub)
print("\nMRO:", Professor.__mro__)
print("\nCalling display_info():")
p.display_info()
SET C
Abstraction – Payment System:-
from abc import ABC, abstractmethod
class Payment(ABC):
@abstractmethod
def make_payment(self, amount):
pass
class CreditCardPayment(Payment):
def make_payment(self, amount):
print("Paid", amount, "using Credit Card")
class UPIPayment(Payment):
def make_payment(self, amount):
print("Paid", amount, "using UPI")
class NetBankingPayment(Payment):
def make_payment(self, amount):
print("Paid", amount, "using Net Banking")
# User input
amount = float(input("Enter payment amount: "))
c = CreditCardPayment()
u = UPIPayment()
n = NetBankingPayment()
c.make_payment(amount)
u.make_payment(amount)
n.make_payment(amount)
Assignment 4: Exception handling
SET A
1. Handle division by zero using try and except:-
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
result = a / b
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
2. Handle ValueError if input is not integer:-
try:
num = int(input("Enter an integer: "))
print("You entered:", num)
except ValueError:
print("Error: Please enter a valid integer.")
3. Handle FileNotFoundError:-
try:
file = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()
except FileNotFoundError:
print("Error: File not found.")
4. Catch ValueError and TypeError:-
try:
value = input("Enter a number: ")
number = int(value)
print("Converted integer:", number)
except ValueError:
print("Error: Invalid number format.")
except TypeError:
print("Error: Type error occurred.")
5. Catch multiple exceptions in one try block:-
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid input. Please enter numbers.")
6. Custom exception for negative number:-
class NegativeNumberError(Exception):
pass
def check_number(num):
if num < 0:
raise NegativeNumberError("Negative number is not allowed")
else:
print("Number is:", num)
try:
n = int(input("Enter a number: "))
check_number(n)
except NegativeNumberError as e:
print("Error:", e)
7. Using else and finally:-
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid input.")
else:
print("Result:", result)
finally:
print("Program execution completed.")
SET B
1. Handle dictionary key exception:-
data = {"name": "Rahul", "age": 21}
key = input("Enter key: ")
try:
print("Value:", data[key])
except KeyError:
print("Key not found. Default value: Not Available")
2. Reciprocal of list elements:-
numbers = [10, 5, 0, "a", 2]
for n in numbers:
try:
result = 1 / n
print("Reciprocal of", n, "=", result)
except ZeroDivisionError:
print("Cannot calculate reciprocal of 0")
except TypeError:
print("Invalid element:", n)
3. Nested try-except blocks:-
try:
num = int(input("Enter a number: "))
try:
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Inner Error: Division by zero")
except ValueError:
print("Outer Error: Invalid input")
4. Read integers from file and skip invalid data:-
try:
file = open("[Link]", "r")
for line in file:
try:
num = int([Link]())
print("Number:", num)
except ValueError:
print("Invalid data skipped:", [Link]())
[Link]()
except FileNotFoundError:
print("File not found.")
SET C
1. Custom exception for string length:-
class StringLengthError(Exception):
pass
def check_string(text):
if len(text) > 10:
raise StringLengthError("String length exceeds limit")
else:
print("Valid string:", text)
try:
s = input("Enter a string: ")
check_string(s)
except StringLengthError as e:
print("Error:", e)
2. ATM Withdrawal Simulation:-
balance = 5000
try:
withdraw = int(input("Enter amount to withdraw: "))
if withdraw > balance:
raise Exception("Insufficient balance")
balance -= withdraw
print("Withdrawal successful")
print("Remaining balance:", balance)
except Exception as e:
print("Error:", e)
3. Raise ValueError for negative number:-
try:
num = int(input("Enter a number: "))
if num < 0:
raise ValueError("Number cannot be negative")
except ValueError as e:
print("Error:", e)
else:
print("Valid number:", num)
finally:
print("Execution finished")
Assignment 5: Basics of Pandas and Numpy
SET A
1. Create a NumPy array from 1 to 10 and print only even numbers:-
import numpy as np
arr = [Link](1, 11)
even_numbers = arr[arr % 2 == 0]
print("Array:", arr)
print("Even Numbers:", even_numbers)
2. Create a 3×3 ones matrix and calculate its sum:-
import numpy as np
matrix = [Link]((3,3))
total = [Link](matrix)
print("Matrix:\n", matrix)
print("Sum:", total)
3. Create a Series of first 5 prime numbers and find its mean:-
import pandas as pd
primes = [Link]([2, 3, 5, 7, 11])
mean_value = [Link]()
print("Prime Numbers Series:")
print(primes)
print("Mean:", mean_value)
4. Create a DataFrame with Name & Age and print only the Age column:-
import pandas as pd
data = {
"Name": ["Amit", "Riya", "Rahul", "Sneha"],
"Age": [20, 21, 19, 22]
df = [Link](data)
print("Age Column:")
print(df["Age"])
SET B
1. Create a 4×4 matrix and replace values > 10 with 0 :-
import numpy as np
matrix = [Link](1,17).reshape(4,4)
matrix[matrix > 10] = 0
print("Modified Matrix:\n", matrix)
2. Generate 20 random numbers and find mean, median & standard deviation:-
import numpy as np
numbers = [Link](20)
mean = [Link](numbers)
median = [Link](numbers)
std = [Link](numbers)
print("Random Numbers:", numbers)
print("Mean:", mean)
print("Median:", median)
print("Standard Deviation:", std)
3. Load a CSV and display rows where Marks > 80:-
import pandas as pd
df = pd.read_csv("[Link]")
result = df[df["Marks"] > 80]
print(result)
4. Group DataFrame by “Class” and find average marks:-
import pandas as pd
data = {
"Name": ["Amit","Riya","Rahul","Sneha"],
"Class": ["A","A","B","B"],
"Marks": [85, 90, 78, 88]
df = [Link](data)
avg_marks = [Link]("Class")["Marks"].mean()
print(avg_marks)
SET C
1. Multiply two matrices without using [Link]():-
import numpy as np
A = [Link]([[1,2],[3,4]])
B = [Link]([[5,6],[7,8]])
result = [[0,0],[0,0]]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
print("Result Matrix:")
print([Link](result))
2. Clean a dataset
(Remove duplicates, Fill missing values with mean, Sort by two columns):-
import pandas as pd
data = {
"Name": ["Amit","Riya","Amit","Rahul"],
"Marks": [85, None, 85, 90],
"Age": [20, 21, 20, None]
df = [Link](data)
# Remove duplicates
df = df.drop_duplicates()
# Fill missing values with mean
df["Marks"].fillna(df["Marks"].mean(), inplace=True)
df["Age"].fillna(df["Age"].mean(), inplace=True)
# Sort by Marks (ASC) and Age (DESC)
df = df.sort_values(by=["Marks","Age"], ascending=[True, False])
print(df)
Assignment 6: Data Visualization
SET A
1) Line Chart using Matplotlib:-
import [Link] as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 25, 30]
[Link](x, y, label="Sales Data")
[Link]("Simple Line Chart")
[Link]("X Values")
[Link]("Y Values")
[Link]()
[Link]()
2) Bar Chart – Students in Subjects:-
import [Link] as plt
subjects = ["Python", "Java", "C++", "JS"]
students = [50, 40, 30, 45]
[Link](subjects, students, label="Number of Students")
[Link]("Students Enrolled in Subjects")
[Link]("Subjects")
[Link]("Number of Students")
[Link]()
[Link]()
3) Pie Chart – Mobile Market Share:-
import [Link] as plt
brands = ["Samsung", "Apple", "Xiaomi", "Others"]
share = [35, 25, 20, 20]
[Link](share, labels=brands, autopct='%1.1f%%')
[Link]("Mobile Market Share")
[Link]()
4) Histogram – Student Marks:-
import [Link] as plt
marks = [55, 60, 65, 70, 72, 75, 80, 82, 85, 90, 92]
[Link](marks)
[Link]("Histogram of Student Marks")
[Link]("Marks")
[Link]("Frequency")
[Link]()
SET B
1) Scatter Plot – Height vs Weight:-
import [Link] as plt
height = [150, 160, 165, 170, 175, 180]
weight = [55, 60, 62, 68, 75, 80]
[Link](height, weight, marker='o')
[Link]("Height vs Weight")
[Link]("Height (cm)")
[Link]("Weight (kg)")
[Link]()
2) Customized Line Chart:-
import [Link] as plt
x = [1, 2, 3, 4, 5]
y = [5, 10, 15, 8, 20]
[Link](x, y, color='red', linestyle='--', marker='o', label="Data Line")
[Link]("Customized Line Chart")
[Link]("X Axis")
[Link]("Y Axis")
[Link]()
[Link]()
3) Seaborn Boxplot:-
import pandas as pd
import seaborn as sns
import [Link] as plt
data = {
"Maths": [78, 82, 85, 90, 88, 76],
"Science": [70, 75, 80, 85, 82, 78],
"English": [65, 70, 72, 75, 78, 80]
df = [Link](data)
[Link](data=df)
[Link]("Marks Distribution of Subjects")
[Link]()
SET C
1) Student Marks Dataset:-
import pandas as pd
import [Link] as plt
df = pd.read_csv("student_marks.csv")
# a) Column names and shape
print([Link])
print([Link])
# b) Random 5 rows
print([Link](5))
# c) Maximum and minimum marks
print("Maximum Marks:", df["marks"].max())
print("Minimum Marks:", df["marks"].min())
# d) Histogram
[Link](df["marks"])
[Link]("Histogram of Student Marks")
[Link]("Marks")
[Link]("Frequency")
[Link]()
2) Iris Dataset Analysis:-
import pandas as pd
import [Link] as plt
import seaborn as sns
df = pd.read_csv("[Link]")
# a) First 5 rows
print([Link]())
# b) Number of records of each species
print(df["species"].value_counts())
# c) Scatter plot
[Link](df["sepal_length"], df["petal_length"])
[Link]("Sepal Length")
[Link]("Petal Length")
[Link]("Sepal vs Petal Length")
[Link]()
# d) Box plot
[Link](y=df["sepal_width"])
[Link]("Box Plot of Sepal Width")
[Link]()
2) StudentsPerformance Dataset:-
import pandas as pd
import [Link] as plt
df = pd.read_csv("[Link]")
# a) Top 10 rows
print([Link](10))
# b) Check missing values
print([Link]().sum())
# c) Replace missing values with mean
[Link]([Link](numeric_only=True), inplace=True)
# d) Bar chart of average marks
avg_marks = df[["math score", "reading score", "writing score"]].mean()
avg_marks.plot(kind='bar')
[Link]("Average Marks of Students")
[Link]("Subjects")
[Link]("Average Marks")
[Link]()
Assignment 7: Network Programming
SET A
1) TCP Server & Client (Port 50000)
Server Code:-
# server_A1.py
import socket
server = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](("localhost", 50000))
[Link](1)
print("Server started")
conn, addr = [Link]()
print("Client connected:", addr)
[Link]()
[Link]()
Client Code:-
# client_A1.py
import socket
client = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](("localhost", 50000))
print("Connected to server")
[Link]()
2) TCP Server & Client (Port 51000)
Client sends message to server
Server Code:-
# server_A2.py
import socket
server = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](("localhost", 51000))
[Link](1)
print("Server started...")
conn, addr = [Link]()
msg = [Link](1024).decode()
print("Message from client:", msg)
[Link]()
[Link]()
Client Code:-
# client_A2.py
import socket
client = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](("localhost", 51000))
msg = input("Enter message: ")
[Link]([Link]())
[Link]()
SET B
1) Send Number → Server Checks Prime
Server Code:-
# server_B2.py
import socket
server = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](("localhost", 51000))
[Link](1)
print("Server started...")
conn, addr = [Link]()
while True:
msg = [Link](1024).decode()
if [Link]() == "quit":
print("Client ended the chat")
break
print("Client:", msg)
[Link]()
[Link]()
Client Code:-
# client_B2.py
import socket
client = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](("localhost", 51000))
while True:
msg = input("Enter message: ")
[Link]([Link]())
if [Link]() == "quit":
break
[Link]()
SET C
1) Send File from Client to Server
Server Code:-
# server_C1.py
import socket
server = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](("localhost", 50000))
[Link](1)
print("Server started...")
conn, addr = [Link]()
data = [Link](4096).decode()
file = open("[Link]", "w")
[Link](data)
[Link]()
print("File received successfully")
[Link]()
[Link]()
Client Code:- # client_C1.py
import socket
client = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](("localhost", 50000))
filename = input("Enter file name: ")
file = open(filename, "r")
data = [Link]()
[Link]([Link]())
[Link]()
[Link]()
How to Run (Important for Exam / Practical):
1. Run server first
python server_A1.py
2. Then run client:-
python client_A1.py
Assignment 8: Database Connectivity & Visualization
SET A
SET A – Q1 : Create SQLite Table and Insert Records:-
import sqlite3
try:
# Connect to database
conn = [Link]("[Link]")
cursor = [Link]()
# Create table
[Link]("""
CREATE TABLE IF NOT EXISTS students(
id INTEGER PRIMARY KEY,
name TEXT,
marks INTEGER
""")
# Insert 5 records
students = [
(1, "Amit", 85),
(2, "Riya", 90),
(3, "Rahul", 78),
(4, "Sneha", 88),
(5, "Karan", 76)
[Link]("INSERT INTO students VALUES(?,?,?)", students)
[Link]()
print("Record inserted successfully")
except Exception as e:
print("Error:", e)
finally:
[Link]()
Q2 : Retrieve and Display Records:-
import sqlite3
try:
conn = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT * FROM students")
records = [Link]()
print("ID\tName\tMarks")
print("---------------------")
for row in records:
print(row[0], "\t", row[1], "\t", row[2])
except Exception as e:
print("Error:", e)
finally:
[Link]()
SET B
SET B – Q1 : Menu Driven SQLite Program:-
import sqlite3
conn = [Link]("[Link]")
cursor = [Link]()
while True:
print("\[Link] Student")
print("[Link] Students")
print("[Link] Marks")
print("[Link] Student")
print("[Link]")
choice = input("Enter choice: ")
try:
if choice == "1":
id = int(input("Enter ID: "))
name = input("Enter Name: ")
marks = int(input("Enter Marks: "))
[Link]("INSERT INTO students VALUES(?,?,?)",(id,name,marks))
[Link]()
print("Student Inserted")
elif choice == "2":
[Link]("SELECT * FROM students")
for row in [Link]():
print(row)
elif choice == "3":
id = int(input("Enter Student ID: "))
marks = int(input("Enter New Marks: "))
[Link]("UPDATE students SET marks=? WHERE id=?",(marks,id))
[Link]()
print("Marks Updated")
elif choice == "4":
id = int(input("Enter Student ID to Delete: "))
[Link]("DELETE FROM students WHERE id=?",(id,))
[Link]()
print("Record Deleted")
elif choice == "5":
break
else:
print("Invalid Choice")
except Exception as e:
print("Error:",e)
[Link]()
Q2 : PostgreSQL Employee Insert Program:-
import psycopg2
try:
conn = [Link](
database="postgres",
user="postgres",
password="postgres",
host="localhost",
port="5432"
cursor = [Link]()
[Link]("""
CREATE TABLE IF NOT EXISTS employees(
id SERIAL PRIMARY KEY,
name VARCHAR(50),
salary INT
""")
n = int(input("Enter number of employees: "))
count = 0
for i in range(n):
name = input("Enter name: ")
salary = int(input("Enter salary: "))
[Link](
"INSERT INTO employees(name,salary) VALUES(%s,%s)",
(name,salary)
count += 1
[Link]()
print("Rows inserted:", count)
except Exception as e:
print("Error:", e)
finally:
[Link]()
SET C
SET C – Q1 : PostgreSQL Product Management System:-
import psycopg2
try:
conn = [Link](
database="postgres",
user="postgres",
password="postgres",
host="localhost",
port="5432"
cursor = [Link]()
[Link]("""
CREATE TABLE IF NOT EXISTS products(
pid SERIAL PRIMARY KEY,
pname VARCHAR(50),
price INT,
qty INT
""")
[Link]()
except Exception as e:
print("Database connection error:", e)
exit()
while True:
print("\[Link] Product")
print("[Link] Product")
print("[Link] Quantity")
print("[Link] Product")
print("[Link] Products with Price > Value")
print("[Link]")
choice = input("Enter choice: ")
try:
if choice == "1":
pname = input("Enter product name: ")
price = int(input("Enter price: "))
qty = int(input("Enter quantity: "))
if price <= 0 or qty <= 0:
print("Price and quantity must be positive")
continue
[Link](
"INSERT INTO products(pname,price,qty) VALUES(%s,%s,%s)",
(pname,price,qty)
[Link]()
print("Product Added")
elif choice == "2":
name = input("Enter product name: ")
[Link](
"SELECT * FROM products WHERE pname=%s",
(name,)
result = [Link]()
if result:
print(result)
else:
print("Record not found")
elif choice == "3":
name = input("Enter product name: ")
qty = int(input("Enter new quantity: "))
[Link](
"UPDATE products SET qty=%s WHERE pname=%s",
(qty,name)
if [Link] == 0:
print("Record not found")
else:
[Link]()
print("Quantity Updated")
elif choice == "4":
name = input("Enter product name to delete: ")
[Link](
"DELETE FROM products WHERE pname=%s",
(name,)
if [Link] == 0:
print("Record not found")
else:
[Link]()
print("Product Deleted")
elif choice == "5":
price = int(input("Enter price value: "))
[Link](
"SELECT * FROM products WHERE price > %s",
(price,)
records = [Link]()
for r in records:
print(r)
elif choice == "6":
break
else:
print("Invalid choice")
except ValueError:
print("Invalid numeric input")
except Exception as e:
print("Error:", e)
[Link]()