Python Programming
Lab - Part B
AKSHAY P.V
Lecturer
BCA
Udupi College of Professional Studies.
1. Program to create a class Employee with empno, name, depname,
designation, age and salary and perform the following function.
i) Accept details of N employees
ii) Search given employee using empno
iii) display employee details in neat format
class Employee:
def __init__(self, empno, name, depname, designation, age, salary):
[Link] = empno
[Link] = name
[Link] = depname
[Link] = designation
[Link] = age
[Link] = salary
def display(self):
print(f"{[Link]:<10}{[Link]:<15}{[Link]:<15}"
f"{[Link]:<15}{[Link]:<5}{[Link]:<10}")
# i) Accept details of N employees
n = int(input("Enter number of employees: "))
emp_list = []
for i in range(n):
print(f"\nEnter details of employee {i+1}")
empno = int(input("Emp No: "))
name = input("Name: ")
depname = input("Department: ")
designation = input("Designation: ")
age = int(input("Age: "))
salary = float(input("Salary: "))
emp = Employee(empno, name, depname, designation, age, salary)
emp_list.append(emp)
# ii) Search employee using empno
search_no = int(input("\nEnter employee number to search: "))
found = False
print("\nEmployee Details")
print("-" * 70)
print(f"{'EmpNo':<10}{'Name':<15}{'Department':<15}"
f"{'Designation':<15}{'Age':<5}{'Salary':<10}")
print("-" * 70)
for emp in emp_list:
if [Link] == search_no:
[Link]()
found = True
break
if not found:
print("Employee not found")
2. Write a program menu-driven to create a BankAccount class, class
should support the following method for
i) Deposit
ii) Withdraw
iii) GetBalance
Create a subclass SavingsAccount class that behaves just like a
BankAccount, but also has an interest rate and a method that
increases the balance by the appropriate amount of interest.
class BankAccount:
def __init__(self, accno, name, balance=0):
[Link] = accno
[Link] = name
[Link] = balance
# Deposit method
def deposit(self, amount):
[Link] += amount
print("Amount deposited successfully.")
# Withdraw method
def withdraw(self, amount):
if amount > [Link]:
print("Insufficient balance.")
else:
[Link] -= amount
print("Amount withdrawn successfully.")
# Get balance method
def getBalance(self):
print("Current Balance:", [Link])
# Subclass
class SavingsAccount(BankAccount):
def __init__(self, accno, name, balance, interest_rate):
super().__init__(accno, name, balance)
self.interest_rate = interest_rate
# Method to add interest
def add_interest(self):
interest = [Link] * self.interest_rate / 100
[Link] += interest
print("Interest added:", interest)
# Main Program (Menu Driven)
accno = int(input("Enter Account Number: "))
name = input("Enter Account Holder Name: ")
balance = float(input("Enter Initial Balance: "))
rate = float(input("Enter Interest Rate (%): "))
account = SavingsAccount(accno, name, balance, rate)
while True:
print("\n--- MENU ---")
print("1. Deposit")
print("2. Withdraw")
print("3. Get Balance")
print("4. Add Interest")
print("5. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
amt = float(input("Enter amount to deposit: "))
[Link](amt)
elif choice == 2:
amt = float(input("Enter amount to withdraw: "))
[Link](amt)
elif choice == 3:
[Link]()
elif choice == 4:
account.add_interest()
elif choice == 5:
print("Thank you!")
break
else:
print("Invalid choice")
3. Create a GUI to input principal amount, rate of interest and
number of years. Calculate Compound Interest, when button
submit is pressed. Compound interest should be displayed in a
textbox. When clear button is pressed all contents should be
cleared.
import tkinter as tk
# Function to calculate compound interest
def calculate_ci():
p = float(entry_principal.get())
r = float(entry_rate.get())
t = float(entry_years.get())
ci = p * ((1 + r/100) ** t) - p
textbox_result.delete(0, [Link])
textbox_result.insert(0, str(round(ci,2)))
# Function to clear all fields
def clear_all():
entry_principal.delete(0, [Link])
entry_rate.delete(0, [Link])
entry_years.delete(0, [Link])
textbox_result.delete(0, [Link])
# Create window
window = [Link]()
[Link]("Compound Interest Calculator")
[Link]("350x250")
# Labels
[Link](window, text="Principal Amount").pack()
entry_principal = [Link](window)
entry_principal.pack()
[Link](window, text="Rate of Interest (%)").pack()
entry_rate = [Link](window)
entry_rate.pack()
[Link](window, text="Number of Years").pack()
entry_years = [Link](window)
entry_years.pack()
[Link](window, text="Compound Interest").pack()
textbox_result = [Link](window)
textbox_result.pack()
# Buttons
submit_btn = [Link](window, text="Submit", command=calculate_ci)
submit_btn.pack(pady=5)
clear_btn = [Link](window, text="Clear", command=clear_all)
clear_btn.pack()
# Run the GUI
[Link]()
4. Write a GUI program to implement simple calculator?
import tkinter as tk
# Function for addition
def add():
n1 = float([Link]())
n2 = float([Link]())
result = n1 + n2
entry_result.delete(0, [Link])
entry_result.insert(0, str(result))
# Function for subtraction
def subtract():
n1 = float([Link]())
n2 = float([Link]())
result = n1 - n2
entry_result.delete(0, [Link])
entry_result.insert(0, str(result))
# Function for multiplication
def multiply():
n1 = float([Link]())
n2 = float([Link]())
result = n1 * n2
entry_result.delete(0, [Link])
entry_result.insert(0, str(result))
# Function for division
def divide():
n1 = float([Link]())
n2 = float([Link]())
result = n1 / n2
entry_result.delete(0, [Link])
entry_result.insert(0, str(result))
# Function to clear all fields
def clear():
[Link](0, [Link])
[Link](0, [Link])
entry_result.delete(0, [Link])
# Create window
window = [Link]()
[Link]("Simple Calculator")
[Link]("300x250")
# Labels
[Link](window, text="First Number").pack()
entry1 = [Link](window)
[Link]()
[Link](window, text="Second Number").pack()
entry2 = [Link](window)
[Link]()
[Link](window, text="Result").pack()
entry_result = [Link](window)
entry_result.pack()
# Buttons
[Link](window, text="Add", command=add).pack()
[Link](window, text="Subtract", command=subtract).pack()
[Link](window, text="Multiply", command=multiply).pack()
[Link](window, text="Divide", command=divide).pack()
[Link](window, text="Clear", command=clear).pack()
# Run GUI
[Link]()
5. Create a table student table(regno, name and marks in 3
subjects) using MySQL/SQLite and perform the following
a) To accept the details of students and store in database
b) To display the details of all the students
c) Delete particular student record using regno
import sqlite3
conn = [Link]("[Link]") # Cell 1: Create Database & Table
cursor = [Link]()
[Link]("""
CREATE TABLE IF NOT EXISTS student (
regno INTEGER PRIMARY KEY,
name TEXT,
sub1 INTEGER,
sub2 INTEGER, Output 1:
sub3 INTEGER Table created successfully
)
""")
[Link]()
print("Table created successfully")
#Cell-2: Inserting the values to student
def add_student(regno, name, sub1, sub2, sub3):
[Link]("INSERT INTO student VALUES (?, ?, ?, ?, ?)",
(regno, name, sub1, sub2, sub3))
[Link]()
print("Record inserted")
add_student(101, "Akshay", 80, 75, 90) Output 2:
add_student(102, "Ravi", 70, 85, 88) Record inserted
Record inserted
#Cell 3: Display Student details
def display_students():
[Link]("SELECT * FROM student")
rows = [Link]()
print("RegNo | Name | Sub1 | Sub2 | Sub3")
for row in rows:
print(row) Output 3:
display_students() RegNo | Name | Sub1 | Sub2 | Sub3
(101, 'Akshay', 80, 75, 90)
(102, 'Ravi', 70, 85, 88)
# Cell 4: Delete student detail of 101
def delete_student(regno):
[Link]("DELETE FROM student WHERE regno = ?", (regno,))
[Link]()
print("Record deleted")
Output 4:
Record deleted
delete_student(101) RegNo | Name | Sub1 | Sub2 | Sub3
display_students() (102, 'Ravi', 70, 85, 88)
6. Create a table employee (empno, name and salary) using
MySQL/SQLite and perform the following
a) To accept the details of employees and store it in
database.
b) To display the details of a specific employee.
c) To display employee details whose salary lies within a
certain range.
import sqlite3
conn = [Link]("[Link]")
cursor = [Link]()
[Link]("""
CREATE TABLE IF NOT EXISTS employee (
empno INTEGER PRIMARY KEY,
name TEXT,
salary REAL
)
""")
[Link]()
print("Employee table created successfully")
# Cell 2: part A
def add_employee(empno, name, salary):
[Link]("INSERT INTO Employee VALUES (?, ?, ?)",
(empno, name, salary))
[Link]()
print("Employee record inserted")
add_employee(1, "Akshay", 25000)
add_employee(2, "Ravi", 30000)
add_employee(3, "Anu", 40000)
#Cell 3: part B
def display_employee(empno):
[Link]("SELECT * FROM employee WHERE empno = ?",
(empno,))
row = [Link]()
if row:
print("EmpNo | Name | Salary")
print(row)
else:
print("Employee not found")
display_employee(2)
#Cell 4: Part C
def display_by_salary(min_salary, max_salary):
[Link]("SELECT * FROM employee WHERE salary BETWEEN ?
AND ?",
(min_salary, max_salary))
rows = [Link]()
print("EmpNo | Name | Salary")
for row in rows:
print(row)
display_by_salary(25000, 35000)
Step 1: Create CSV file
1. Open Excel
2. Enter data in columns:
Batsmen 2017 2018 2019 2020
Virat Kohli 2501 1855 2203 1223
Steve Smith 2340 2250 2003 1153
Babar Azam 1750 2147 1896 1008
Rohit Sharma 1463 1985 1854 1638
Kane Williamson 1256 1785 1874 1974
Jos Butler 1125 1853 1769 1436
3. Click File → Save As
4. Choose file type: CSV (Comma delimited)
5. Save as [Link]
Step 2 - Upload CSV File
In Jupyter:
1. Click Upload
2. Select [Link]
3. Click Upload
Step 3: Write Code in new cell
import pandas as pd
import [Link] as plt
import numpy as np
data = pd.read_csv("[Link]") # Read CSV
# Extract values
batsmen = data["Batsmen"]
runs_2017 = data["2017"]
runs_2018 = data["2018"]
runs_2019 = data["2019"]
runs_2020 = data["2020"]
# Bar positions
x = [Link](len(batsmen))
width = 0.2
# Plot
[Link](x - 1.5*width, runs_2017, width, label='2017')
[Link](x - 0.5*width, runs_2018, width, label='2018')
[Link](x + 0.5*width, runs_2019, width, label='2019')
[Link](x + 1.5*width, runs_2020, width, label='2020')
# Labels
[Link]("Batsmen")
[Link]("Runs")
[Link]("Runs Scored by Batsmen (2017-2020)")
[Link](x, batsmen, rotation=30)
[Link]()
[Link]()
“While running, If any error has found like library not found, run this command,”
!pip install pandas matplotlib openpyxl
Output: