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

II Sem Bca Python Lab

The document contains a series of Python programming exercises for a Python lab course, covering topics such as list manipulation, area calculations for various shapes, tuple operations, character frequency counting, string comparison, file handling, and data frame operations using pandas. It also includes object-oriented programming examples with classes for Employee and BankAccount, as well as a GUI application for calculating compound interest. Each section provides code snippets, expected outputs, and user interaction prompts.

Uploaded by

saragaffor58
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)
3 views47 pages

II Sem Bca Python Lab

The document contains a series of Python programming exercises for a Python lab course, covering topics such as list manipulation, area calculations for various shapes, tuple operations, character frequency counting, string comparison, file handling, and data frame operations using pandas. It also includes object-oriented programming examples with classes for Employee and BankAccount, as well as a GUI application for calculating compound interest. Each section provides code snippets, expected outputs, and user interaction prompts.

Uploaded by

saragaffor58
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

CLASS: II BCA ROLL NO: PYTHON LAB

1. A program to create list with ‘N’ elements. Find all unique elements in the list,
then add that elements to the unique_list.

n=int (input("enter the size of the list:"))

mylist=[]

for i in range(n):

num=int(input("enter the numbers:"))

[Link](num)

unique_list=[]

for i in mylist:

if [Link](i)==1:

unique_list.append(i)

print("unique elements are:",unique_list)

OUTPUT:

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

2. Program using user defined function to find the area of a rectangle, square,
triangle by accepting suitable input parameters from user.

def rectangle_area(length,width):

area=length*width

return area

def square_area(side):

area=side**2

return area

def circle_area(radius):

area=3.14159*radius**2

return area

def triangle_area(base,height):

area=0.5*base*height

return area

print("Choose a shape to find its area:")

print("[Link]")

print("[Link]")

print("[Link]")

print("[Link]")

choice=int(input("enter your choice:"))

if choice==1:

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

length=float(input("enter the length of rectangle:"))

width=float(input("enter the width:"))

area=rectangle_area(length,width)

print("the area of rectangle is:",area," [Link]")

elif choice==2:

side=float(input("enter the length of a side of the square:"))

area=square_area(side)

print("the area of square is:",area," [Link]")

elif choice==3:

radius=float(input("enter the radius:"))

area=circle_area(radius)

print("the area of circle is:",area," [Link]")

elif choice==4:

base=float(input("enter the base of the triangle:"))

height=float(input("enter the height:"))

area=triangle_area(base,height)

print("the area of triangle is:",area," [Link]")

else:

print("invalid choice")

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

OUTPUT:

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

3. Consider a Tuple t1= (1,2,5,7,9,2,4,6,8,10). Write a program to perform the


following operations:

a) Print half the values of tuple in one line and the other half in the next line.

b) Print another tuple whose values are even number in the given tuple.

c) Concatenate a tuple t2= (11,13,15) with t1.

d) Return maximum and minimum value from this tuple.

t1=(1,2,5,7,9,2,4,6,8,10)

t2=(11,13,15)

print("\nHalf the values of f1 in one line and the other half in the next line")

half_len=len(t1)//2

print(t1[:half_len])

print(t1[half_len:])

t2=()

for i in t1:

if i%2==0:

t2+=(i,)

print("Another tuple whose value are even number in the given tuple:",t2)

print("\nTuple t2 is:",t2,"\n")

t3=t1+t2

print("\nA tuple t2=(11,13,15) concatenated with t1,i.e.,(t1+t2):",t3)

print("\n",t3)

max_value=max(t3)

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

min_value=min(t3)

print("\nMax value from t3:",max_value)

print("\nMin value from t3:",min_value)

OUTPUT:

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

4. Write a function that takes a sentence as input from the user and calculates the
frequency of each letter. Use a variable of dictionary type to maintain the count.

def char_count(sentence):

char_count_dict={}

for character in sentence:

if [Link]():

character=[Link]()

if character in char_count_dict:

char_count_dict[character]+=1

else:

char_count_dict[character]=1

for key,value in char_count_dict.items():

if value!=1:

print(f"the character '{key}' appears {value} times")

else:

print(f"the character '{key}' appears once")

sentence=input("enter a sentence:")

char_count(sentence)

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

OUTPUT:

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

5. Write a function nearly_equal to test whether two strings are equal. Two strings A
and B are nearly equal, if one character changes in B results in string A.

def nearly_equal(str1,str2):

if abs(len(str1)-len(str2))>1:

print("the strings are not equal")

return

no_match_count=0

for i in range(min(len(str1),len(str2))):

if(str1[i]!=str2[i]):

no_match_count+=1

no_match_count+=abs(len(str1)-len(str2))

if no_match_count==0:

print("the two strings entered are equal")

elif no_match_count==1:

print("the two entered strings are nearly equal")

else:

print("the two strings entered are not equal")

str1=input("enter a sentence for string 1:")

str2=input("enter a sentence for string 2:")

nearly_equal(str1,str2)

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

OUTPUT:

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

6. Write a program to create a text file and compute the number of characters, words
and lines in a file.

import os

def count_characters(filename):

with open(filename,"r") as f:

characters=len([Link]())

return characters

def count_words(filename):

with open(filename,"r") as f:

words=len([Link]().split())

return words

def count_line(filename):

with open(filename,"r") as f:

lines=len([Link]())

return lines

def main():

filename=input("enter filename with complete path:")

if not [Link](filename):

with open(filename,"w")as f:

print("enter data to store in file:")

data=input()

while [Link]()!="EOF":

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

[Link](data+"\n")

data=input()

characters=count_characters(filename)

words=count_words(filename)

lines=count_line(filename)

print("the file {} has {} chracters, {} words and {}


lines.".format(filename,characters,words,lines))

if __name__=="__main__":

main()

OUTPUT:

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

7. Write a pandas program to join the two given data frames along rows. Sample
data frames may contain details of students like rollno, name, total marks.

import pandas as pd

data1={

'roll_no':[101,102,103],

'student_name':['akhil','krishna','raaju'],

'total marks':[490,470,420]

df1=[Link](data1)

data2={

'roll_no':[104,105,106],

'student_name':['rohit','virat','dhoni'],

'total marks':[480,460,450]

df2=[Link](data2)

print("DataFrame 1:\n",df1)

print("dataFrame 2:\n",df2)

result_df=[Link]([df1,df2],ignore_index=True)

print("\n joined DataFrame:\n",result_df)

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

OUTPUT:

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

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

[Link] = 0

[Link] = ""

[Link] = ""

[Link] = ""

[Link] = 0

[Link] = 0

def getDetails(self):

[Link] = int(input("Enter employee number: "))

[Link] = input("Enter name: ")

[Link] = input("Enter department name: ")

[Link] = input("Enter designation: ")

[Link] = int(input("Enter age: "))

[Link] = int(input("Enter salary: "))

def showDetails(self):

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

print("\nEmployee No:", [Link])

print("Name:", [Link])

print("Department:", [Link])

print("Designation:", [Link])

print("Age:", [Link])

print("Salary:", [Link])

def search_employee(emp_list, eno):

for e in emp_list:

if [Link] == eno:

return e

return None

emp_list = [] # Main Menu Program

while True:

print("\n----- MENU -----")

print("1. Add Employees")

print("2. Display All Employees")

print("3. Search Employee")

print("4. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

n = int(input("Enter number of employees: "))

for i in range(n):

print("\nEnter details of employee", i+1)

emp = Employee()

[Link]()

emp_list.append(emp)

elif choice == 2:

if len(emp_list) == 0:

print("No employee records found.")

else:

print("\n--- Employee Details ---")

for e in emp_list:

[Link]()

elif choice == 3:

eno = int(input("Enter employee number to search: "))

result = search_employee(emp_list, eno)

if result is not None:

print("\nEmployee Found:")

[Link]()

else:

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

print("Employee not found")

elif choice == 4:

print("Exiting program...")

break

else:

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

OUTPUT:

2. Write a program menu driven to create a BankAccount class. class should support
the following methods for

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

i) Deposit
ii) Withdraw
iii) GetBalanace .
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):

[Link] = int(input("Enter account number: "))

[Link] = input("Enter account holder name: ")

[Link] = float(input("Enter initial balance: "))

def deposit(self):

amt = float(input("Enter amount to deposit: "))

[Link] += amt

print("Amount deposited successfully")

def withdraw(self):

amt = float(input("Enter amount to withdraw: "))

if amt > [Link]:

print("Insufficient balance")

else:

[Link] -= amt

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

print("Amount withdrawn successfully")

def get_balance(self):

print("Current Balance:", [Link])

class SavingAccount(BankAccount):

def __init__(self):

super().__init__()

[Link] = float(input("Enter interest rate (%): "))

def add_interest(self):

interest = ([Link] * [Link]) / 100

[Link] += interest

print("Interest added:", interest)

# Create account

acc = SavingAccount()

# Menu-driven program

while True:

print("\n----- MENU -----")

print("1. Deposit")

print("2. Withdraw")

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

print("3. Check Balance")

print("4. Add Interest")

print("5. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:

[Link]()

elif choice == 2:

[Link]()

elif choice == 3:

acc.get_balance()

elif choice == 4:

acc.add_interest()

elif choice == 5:

print("Exiting program...")

break

else:

print("Invalid choice!")

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

OUTPUT:

[Link] a GUI to input Principal amount, rate of interest and number of years,
Calculate Compound interest. When button submit is pressed Compound interest

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

should be displayed in a textbox. When clear button is pressed all contents should be
cleared.

import tkinter as tk

from tkinter import messagebox

def clear_text():

[Link](0, 'end')

[Link](0, 'end')

[Link](0, 'end')

sample_text.delete(0, 'end')

# Function to calculate compound interest

def calculate_CI():

try:

p = float([Link]())

r = float([Link]())

t = float([Link]())

amount = p * (1 + (r / 100)) ** t

compound_interest = amount - p

sample_text.delete(0, "end")

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

sample_text.insert(0, f"{compound_interest:.2f}")

except ValueError:

[Link]("Error", "Please enter valid numbers!")

# Create main window

root = [Link]()

[Link]("290x175")

[Link]("Compound Interest Calculator")

# Principal

label1 = [Link](root, text="Principal (Rs.): ")

entry1 = [Link](root)

[Link](row=1, column=0)

[Link](row=1, column=1)

# Rate

label2 = [Link](root, text="Rate (%): ")

entry2 = [Link](root)

[Link](row=2, column=0)

[Link](row=2, column=1)

# Time

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

label3 = [Link](root, text="Time (years): ")

entry3 = [Link](root)

[Link](row=3, column=0)

[Link](row=3, column=1)

# Blank row

label4 = [Link](root, text="")

[Link](row=4, column=0)

# Buttons

calculate_button = [Link](root, text="Calculate\nCompound Interest",


command=calculate_CI)

calculate_button.grid(row=5, column=0, columnspan=2)

clear_button = [Link](root, text="Clear", command=clear_text)

clear_button.grid(row=5, column=2)

# Blank row

label5 = [Link](root, text="")

[Link](row=7, column=0)

# Result label

label6 = [Link](root, text="Compound Interest:")

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

[Link](row=8, column=0)

# Result box

sample_text = [Link](root)

sample_text.grid(row=8, column=1)

# Start GUI

[Link]()

OUTPUT:

[Link] a GUI program to implement Simple Calculator

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

from tkinter import *

def CreateBtn(ch, r, c):

if ch == "=":

btn=Button(root, text=ch, width=10, command=btnEqual,fg="red",bg="navy blue")

[Link](row=r, column=c, columnspan=2, pady=2)

else:

btn=Button(root, text=ch, width=5,

command=lambda: btnClick(ch))

[Link](row=r, column=c, pady=2)

def btnClick(ch):

if ch == "C":

[Link](1.0, END)

elif ch == "+/-":

ans = [Link](1.0, END).strip()

if ans[0:1] == "-":

ans = ans[1:]

else:

ans = "-" + ans

[Link](1.0, END)

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

[Link](END, ans, "right")

elif ch == "1/x":

if len([Link](1.0, END).strip()) > 0:

ans = str(eval([Link](1.0, END)))

ans = "1/" + ans

ans = eval(ans)

[Link](1.0, END)

[Link](END, ans, "right")

else:

[Link](END, ch, "right")

def btnEqual():

ans = eval([Link](1.0, END))

[Link](1.0, END)

[Link](END, ans, "right")

# ----------- UI ----------- #

root = Tk()

[Link]("Cals")

[Link]("200x270")

[Link](background='aqua')

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

txtbox = Text(root, height=2, width=23,bg="light yellow")

[Link](row=0, columnspan=4, padx=5, pady=8)

txtbox.tag_configure("right", justify="right")

lst = ["7", "8", "9", "/",

"4", "5", "6", "*",

"1", "2", "3", "-",

"+/-", "0", ".", "+",

"C", "1/x", "="]

r=1

c=0

for ch in lst:

CreateBtn(ch, r, c)

c += 1

if c > 3:

c=0

r += 1

[Link]()

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

OUTPUT:

5. Create a table student table (regno, name and marks in 3 subjects) using
MySQL/SQLite and perform the followings

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

a. To accept the details of students and store it in database.

b. To display the details of all the students

c. Delete particular student record using regno.

import [Link]

# Connect to MySQL

mydb = [Link](

host="localhost",

user="root",

password="",

database="studentdb"

cursor = [Link]()

# Create table (run once)

[Link]("""

CREATE TABLE IF NOT EXISTS student(

rno INT PRIMARY KEY,

name VARCHAR(50),

m1 INT,

m2 INT,

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

m3 INT

""")

# Function to insert student data

def accept(rno, name, m1, m2, m3):

try:

sql = "INSERT INTO student (rno, name, m1, m2, m3) VALUES (%s, %s, %s, %s,
%s)"

values = (rno, name, m1, m2, m3)

[Link](sql, values)

[Link]()

print("1 row inserted")

except:

[Link]()

print("Error inserting data")

# Function to delete student by roll number

def deleted(rno):

sql = "DELETE FROM student WHERE rno = %s"

[Link](sql, (rno,))

[Link]()

print("1 row deleted")

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

# Function to display all students

def display():

[Link]("SELECT * FROM student")

result = [Link]()

if not result:

print("No records found")

else:

print("\nRNO\tNAME\tM1\tM2\tM3")

for row in result:

print(f"{row[0]}\t{row[1]}\t{row[2]}\t{row[3]}\t{row[4]}")

# Menu-driven program

while True:

print("\n--- STUDENT DATABASE MENU ---")

print("1. Insert Student")

print("2. Display Students")

print("3. Delete Student")

print("4. Exit")

choice = int(input("Enter your choice: "))

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

if choice == 1:

rno = int(input("Enter Roll No: "))

name = input("Enter Name: ")

m1 = int(input("Enter Marks 1: "))

m2 = int(input("Enter Marks 2: "))

m3 = int(input("Enter Marks 3: "))

accept(rno, name, m1, m2, m3)

elif choice == 2:

display()

elif choice == 3:

rno = int(input("Enter Roll No to delete: "))

deleted(rno)

elif choice == 4:

print("Exiting...")

break

else:

print("Invalid choice")

OUTPUT:

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

6. Create a table employee (empno, name and salary) using MySQL/SQLite and
perform the followings

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 [Link]

# Database connection

mydb = [Link](

host="localhost",

user="root",

password="", # add your password if any

database="empdb"

cursor = [Link]()

# Function to insert employee details

def accept(eno, n, s):

try:

sql = "INSERT INTO employee VALUES (%s, %s, %s)"

values = (eno, n, s)

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

[Link](sql, values)

[Link]()

print("1 row inserted successfully")

except:

[Link]()

print("Error inserting data")

# Function to display specific employee

def selected(eno):

sql = "SELECT * FROM employee WHERE empno = %s"

[Link](sql, (eno,))

row = [Link]()

if row:

print("EmpNo\tName\tSalary")

print(row[0], "\t", row[1], "\t", row[2])

else:

print("Employee does not exist")

# Function to display employees within salary range

def display(s, e):

sql = "SELECT * FROM employee WHERE salary >= %s AND salary <= %s"

[Link](sql, (s, e))

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

rows = [Link]()

if rows:

print("EmpNo\tName\tSalary")

for row in rows:

print(row[0], "\t", row[1], "\t", row[2])

else:

print("No employees in this salary range")

# Menu-driven program

while True:

print("\n1. Insert Employee")

print("2. Display Specific Employee")

print("3. Display Employees by Salary Range")

print("4. Exit")

ch = int(input("Enter your choice: "))

if ch == 1:

eno = int(input("Enter Emp No: "))

name = input("Enter Name: ")

salary = int(input("Enter Salary: "))

accept(eno, name, salary)

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

elif ch == 2:

eno = int(input("Enter Emp No to search: "))

selected(eno)

elif ch == 3:

s = int(input("Enter Start Salary: "))

e = int(input("Enter End Salary: "))

display(s, e)

elif ch == 4:

print("Exiting program...")

break

else:

print("Invalid choice")

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

OUTPUT:

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

[Link] following data and draw the bar graph using matplot library.(Use CSV
or Excel).

Display appropriate title for axis and chart. Also show legends.

from tkinter import *

import pandas as pd

import [Link] as pit

from tkinter import messagebox

def Add():

bats=[Link]()

scores=[[Link](),[Link](),[Link](),[Link]()]

with open("[Link]","a") as f:

[Link](f"{bats},{",".join(scores)}\n")

[Link]("batsman","details saved")

[Link](0,END)

[Link](0,END)

[Link](0,END)

[Link](0,END)

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

[Link](0,END)

def showplot():

data=pd.read_csv("[Link]")

[Link](x="Batsman",kind="bar",title="scorecard" ,xlabel="Batsman",ylabel="Runs")

[Link]()

with open("[Link]","w")as f:

[Link]("Batsman,2017,2018,2019,2020\n")

root=Tk()

[Link]("scores")

[Link]("200x250")

lbb=Label(root,text="Batsman")

lbsco=Label(root,text="score")

lb2017=Label(root,text="2017")

lb2018=Label(root,text="2018")

lb2019=Label(root,text="2019")

lb2020=Label(root,text="2020")

[Link](row=1,column=0,padx=5,pady=5)

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

[Link](row=2,column=0,padx=5,pady=5)

[Link](row=3,column=0,padx=5,pady=5)

[Link](row=4,column=0,padx=5,pady=5)

[Link](row=5,column=0,padx=5,pady=5)

[Link](row=6,column=0,padx=5,pady=5)

baf=Entry(root)

f2017=Entry(root)

f2018=Entry(root)

f2019=Entry(root)

f2020=Entry(root)

[Link](row=1,column=1)

[Link](row=3,column=1)

[Link](row=4,column=1)

[Link](row=5,column=1)

[Link](row=6,column=1)

addbtn=Button(root,text="Add",command=Add)

plotbtn=Button(root,text="plot",command=showplot)

[Link](row=7,column=0,padx=5,pady=5)

[Link](row=7,column=1,padx=5,pady=5)

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

[Link]()

OUTPUT:

BFGCK KUNDAPURA Page no:


CLASS: II BCA ROLL NO: PYTHON LAB

BFGCK KUNDAPURA Page no:

You might also like