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

Program 9 20

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 views21 pages

Program 9 20

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

PROGRAM 9

import pickle
stud={}
stufile1=open("[Link]","wb")
ans='y'
while ans=='y':
rno=int(input("Enter roll number:"))
name=input("Enter name:")
mark1=int(input("Enter English mark:"))
mark2=int(input("Enter Maths mark:"))
mark3=int(input("Enter CS mark:"))
stud["Rollno"]=rno
stud["Name"]=name
stud["Mark1"]=mark1
stud["Mark2"]=mark2
stud["Mark3"]=mark3
[Link](stud,stufile1)
ans=input("Do u want to append more records?(y/n)...?")
[Link]()

#UPDATING RECORDS IN A BINARY FILE


import pickle
stud={}
found=False
stufile1=open("[Link]","rb+")
print("Student Details")
rno1=int(input("Enter roll number:"))
try:
while True:
rpos=[Link]()
stud=[Link](stufile1)
if stud["Rollno"]==rno1:
stud["Mark1"]+=5
[Link](rpos)
[Link](stud,stufile1)
print(stud)
found=True
except EOFError:
if found==False:
print("Record not found")
else:
print("Record updated")
[Link]()

PROGRAM 9
PROBLEM DEFINITION:
write a Python program that creates a binary file, inputs a roll number, and
updates the marks of the students.

OUTPUT:
_________________________________________________________________________________________

PROGRAM 10:
stack=[ ]
def view( ):
viewStack = stack[::-1]
for x in range(len(viewStack)):
print(viewStack[x])
def push( ):
item=int(input("Enter integer value"))
[Link](item)
def pop( ):
if(stack==[ ]):
print("Stack is Empty")
else:
item=[Link](-1)
print("Deleted element:",item)
def peek( ):
item=stack[-1]
print("Peeked element:",item)
print("Stack operation")
print("************")
print("[Link]")
print("[Link]")
print("[Link]")
print("[Link]")
while True:
choice=int(input("Enter your choice"))
if choice==1:
view( )
elif choice==2:
push( )
elif choice==3:
pop( )
elif choice==4:
peek( )
else:
print("Wrong choice")

PROGRAM 10
PROBLEM DEFINITION:
To Write a Python Program to implement a stack using list.

OUTPUT:

5
67
6
45
Enter your choice4
Peeked element: 5

_____________________________________________________________________________

Program 11

SQL COMMANDS:
1. To display the total number of teachers Department wise.

Ans: SELECT DEPARTMENT,COUNT(*) FROM TEACHER


GROUP BY DEPARTMENT;

Output
Department Count(*)

Computer Science 2
History 3
Mathematics 3

2. To display the teacher details who have been posted in “Delhi”.


Ans: SELECT * FROM TEACHER NATURAL JOIN POSTING WHERE PLACE =
'Delhi';

OUTPUT:

3. To display the highest salary being paid in each department.

Ans: SELECT DEPARTMENT, MAX(SALARY) FROM TEACHER GROUP BY


DEPARTMENT;

OUTPUT:
Department Max(salary)
Computer Science 21000
History 40000
Mathematics 30000

4. To display the total salary being paid for male and female separately

Ans: SELECT GENDER, SUM(SALARY) FROM TEACHER GROUP BY


GENDER;

OUTPUT:

5. To increase the salary for the teachers by 10% who have joined in the year 2017 and
2018.

Ans:
UPDATE TEACHER
SET SALARY = SALARY+SALARY*0.1
WHERE DATE_OF_JOIN BETWEEN ‘2017-01-01’ AND ‘2018-12-31’;

OUTPUT:
3 rows updated
____________________________________________________________________________________________
Program 12
import [Link] as sqltor

def Display(cursor):
[Link]("select * from student")
data = [Link]()
count = [Link]
print("Rows: ", count)
print("%10s %15s %9s %15s %20s %10s" % ("AdmnNo.", "Name", "Gender", "DOB", "Stream",
"Average"))
for row in data:
print("%10s %15s %9s %15s %20s %10s" % (row[0], row[1], row[2], row[3], row[4],
row[5]))

def Select(cursor):
[Link]("select count(*) from student where gender='m' and stream = 'Commerce'")
data = [Link]()
print("4. Number of Male Commerce students", data[0][0])

def Update(cursor):
try:
print("3. Updation of the average")
[Link]("Update student set average=average+5 where stream='Science'")
[Link]()
print("Update successful")
except:
print("Updation not possible since the average is exceeding 100")

def Delete(cursor):
print("5. Deleting the records whose average is < 40")
[Link]("delete from student where average < 40")
[Link]()
print("After Deletion")
Display(cursor)

# Main Program
mycon = [Link](host="localhost", user="root", passwd="Shan@p6iya", database="sys")

if mycon.is_connected():
print("Successful")

cursor = [Link]()

[Link]("create table student(admno int primary key, sname varchar(20), gender


char(1), dob date, stream varchar(20), average float(5,2) check (average>=0 and
average<=100))")
print("1. Table created")

[Link]("insert into student values(1023, 'aaa', 'm', '2001-01-01', 'Science', 98)")


[Link]("insert into student values(1045, 'bbb', 'f', '2000-11-11', 'Commerce',
90)")
[Link]("insert into student values(1010, 'ccc', 'm', '2002-11-21', 'Science', 33)")
[Link]("insert into student values(1012, 'ddd', 'm', '2001-05-11', 'Commerce',
89)")
[Link]("insert into student values(1001, 'eee', 'm', '2000-12-10', 'Commerce',
98)")
[Link]()
print("2. 5 Records Inserted")

Display(cursor)
Select(cursor)
Update(cursor)
Delete(cursor)
[Link]()
Program 12
PROGRAM DEFINITION:
Program to connect python with MYSQL using database connectivity and perform the
following operation on data in database:
Insert, Fetch, Update and Delete the data.
i)Create a table student with admno, sname,gender,dob,stream,average.
ii)Insert 5 records into the students table by accepting from the user.
iii)Increase the marks by 5 for those students who belong to science stream.
iv)Display the number of male student who belong to commerce stream
v)Delete the records of those students whose average <40.
OUTPUT:
Successful
1. Table created
2. 5 Records Inserted
Rows: 5
AdmnNo. Name Gender DOB Stream Average
1001 eee m 2000-12-10 Commerce 98.0
1010 ccc m 2002-11-21 Science 33.0
1012 ddd m 2001-05-11 Commerce 89.0
1023 aaa m 2001-01-01 Science 98.0
1045 bbb f 2000-11-11 Commerce 90.0
4. Number of Male Commerce students 2
3. Updation of the average
Updation not possible since the average is exceeding 100
5. Deleting the records whose average is < 40
After Deletion
Rows: 4
AdmnNo. Name Gender DOB Stream Average
1001 eee m 2000-12-10 Commerce 98.0
1012 ddd m 2001-05-11 Commerce 89.0
1023 aaa m 2001-01-01 Science 98.0
1045 bbb f 2000-11-11 Commerce 90.0
_____________________________________________________________________
PROGRAM 13:
import [Link] as sqltor
mycon = [Link](host="localhost", user="root", passwd="Shan@p6iya", database="sys")
if mycon.is_connected():
print("Successful")
cursor = [Link]()
[Link]("CREATE TABLE Event(eventid INT PRIMARY KEY, Eventname VARCHAR(20),
Noperf INT, CelebrityID VARCHAR(5))")
print("1. Table Event Created")
[Link]("CREATE TABLE Celebrity(CelebrityID VARCHAR(5) PRIMARY KEY, Name
VARCHAR(20), Phone INT, Feecharged FLOAT(10, 2))")
print("2. Table Celebrity Created")

def insertevent():
[Link]("INSERT INTO Event VALUES(101, 'Birthday', 10, 'C102')")
[Link]("INSERT INTO Event VALUES(102, 'PromotionParty', 20, 'C103')")
[Link]("INSERT INTO Event VALUES(103, 'Engagement', 12, 'C102')")
[Link]("INSERT INTO Event VALUES(104, 'Wedding', 15, 'C104')")
[Link]("INSERT INTO Event VALUES(105, 'Birthday', 17, 'C101')")
print("2. Records inserted for Event Table")
[Link]("SELECT * FROM Event")
data = [Link]()
count = [Link]
print("Rows:", count)
print("%10s" % "Event Id.", "%15s" % "EventName", "%9s" % "No. of Performers", "%15s" %
% “CelebrityId")
for row in data:
print("%10s" % row[0], "%15s" % row[1], "%9s" % row[2], "%15s" % row[3])

def insertcelebrity():
[Link]("INSERT INTO Celebrity VALUES('C101', 'Faiz Khan', 991019560, 200000)")
[Link]("INSERT INTO Celebrity VALUES('C102', 'Sanjay Kumar', 893466448,
1 250000)")
[Link]("INSERT INTO Celebrity VALUES('C103', 'Neer Khan Kapoor', 981165685,
1 300000)")
[Link]("INSERT INTO Celebrity VALUES('C104', 'Reena Bhatia', 658777564,
1 100000)")
print("[Link] inserted for Celebrity Table")
[Link]("SELECT * FROM Celebrity")
data = [Link]()
print("%15s" % "Celebrity Id.", "%25s" % "Name", "%13s" % "Phone No.", "%15s" %
1 "Feecharged")
for row in data:
print("%15s" % row[0], "%25s" % row[1], "%13s" % row[2], "%15s" % row[3])

def Display():
print("[Link] Eventname, Celebrity name, and feecharged for events where
1 Feecharged is more than 200,000")
[Link]("SELECT Eventname, Name, Feecharged FROM Event, Celebrity WHERE
1 [Link] = [Link] AND Feecharged > 200000")
data = [Link]()
count = [Link]
print("Rows:", count)
print("%15s" % "Event Name", "%25s" % "Name", "%15s" % "Feecharged")
for row in data:
print("%15s" % row[0], "%25s" % row[1], "%15s" % row[2])

def Update():
try:

print("4. Increasing the Feecharged by 10,000 for the events where Number of
1 performers is greater than 15")
[Link]("UPDATE Event, Celebrity SET Feecharged = Feecharged + 10000 WHERE
1 [Link] = [Link] AND Noperf > 15")
[Link]("SELECT * FROM Celebrity")
data = [Link]()
print("%15s" % "Celebrity Id.", "%25s" % "Name", "%13s" % "Phone No.", "%15s" %
"Feecharged")
for row in data:
print("%15s" % row[0], "%25s" % row[1], "%13s" % row[2], "%15s" % row[3])
except Exception as e:
print("Error:", e)

# Main Program
insertevent()
insertcelebrity()
Display()
Update()

# Commit changes and close the connection


[Link]()
[Link]()

PROGRAM 13

PROGRAM DEFINITION:

Program to connect Python with MYSQL using database connectivity and perform the following operations on
data in database:

i) Create 2 tables

Event -EventID,Eventname,NumPerformaers,CelebrityID

Celebrity-CelebrityID,Name,Phone,Feecharged

ii)Insert 5 records in both the table

iii)Display the Eventname,Name of celebrity an Feecharged for those celebrities who charge more than 200000.

iv)Increase the Feecharged by 10000 for the events whose number of Performers is >15.

OUTPUT
______________________________________________________________________________________________

PROGRAM 14:
PROBLEM DEFINITION:
To fetch, update and delete the data of MYSQL using Python.
i)Create 2 Tables
Employee-Empno,Name,Desig,Salary,Leave,Bonus
Insurance-Empno,LIC
ii)Insert 5 records in both the tables by accepting the values of the attributes from the user.
iii)Display the total salary of each designation of those emp whose name starts ‘R’.
iv)Display the Empno and name who has LIC insurance.
v)Update the salary by 10% for those employee whose Desig is Clerk.
OUTPUT:
PROGRAM 14:
PROGRAM 15:
PROBLEM DEFINITION:
Write a program in Python to find the factorial for a given number.

OUTPUT:
Please enter any number to find factorial: 6
The factorial of 6 is: 720

PROGRAM 15:
def factorial(num):
fact=1
for i in range(1, num+1):
fact=fact*i
return fact
number=int(input("Please enter any number to find factorial: "))
result=factorial(number)
print("The factorial of", number ,"is:", result)

_______________________________________________________________________________________________

PROGRAM 16:
PROBLEM DEFINITION:
Write a program in Python to find Fibonacci series for the given term.

OUTPUT:
PROGRAM 16:
n = int(input("Enter the value of n: "))
a = 0
b = 1
sum = 0
count = 1
print("Fibonacci Series: ")
while(count <= n):
print(sum)
count += 1
a = b
b = sum
sum = a + b

_______________________________________________________________________________________________

PROGRAM 17:
PROBLEM DEFINITION:
Write a program in Python to find given string is palindrome or not.

OUTPUT:
Enter string:RACECAR
The given string is Palindrome

PROGRAM 17:
def isPalindrome(str):
for i in range(0, int(len(str)/2)):
if str[i]!=str[len(str)-i-1]:
return False
return True
s=input("Enter string:")
ans = isPalindrome(s)
if (ans):
print("The given string is Palindrome")
else:
print("The given string is not a Palindrome")
PROGRAM 18:
PROBLEM DEFINITION:
To write a Python program to read from the file [Link] and
display all the lines which ends with the word “health”

OUTPUT:
Program using text file [Link]
Creating text file
Enter the line to store:We all need good health
Continuey
Enter the line to store:We must need energy
Continuen
Reading from the file
We all need good health

PROGRAM 18:
def wetxt():
fout=open("[Link]","w")
rep='y'
while (rep=='y'):
s=input("Enter the line to store:")
[Link](s)
[Link]('\n')
rep=input("Continue")
[Link]()
def retxt():
fin=open("[Link]")
for line in fin:
n=[Link]()
if n[len(n)-1]=="health":
print(line)
[Link]()
print("\t\t\t\t\t Program using text file [Link]")
print("Creating text file")
wetxt()
print("Reading from the file")
retxt()
PROGRAM 19:
PROGRAM DEFINITION:
To write a program using functions to create a text
file”[Link]”,read lines from the text file “[Link]” and display those
words whose length is less than 4 character.

File Contents:
this is the sample text file
created for the lab program exercise

OUTPUT:
words less than 4 are
is
the
for
the
lab

PROGRAM 19:
def fourletterwords():
L=[]
x=open ("[Link]")
print("words less than 4 are")
for i in x:
L=[Link]()
for a in L:
if len(a)<4:
print(a)
fourletterwords()
___________________________________________________
PROGRAM 20:
PROBLEM DEFINITION:
To write an interactive Python Program to
i)Accept a list of elements and exchange first half with second half
ii)Accept a list of words and display number of palindromes present in it.

OUTPUT:
PROGRAM 20:
def half_and_half(my_list):
if len(my_list) % 2 == 0:
start = 0
else:
start = 1

L = len(my_list) // 2
for i in range(L):
temp = my_list[i]
my_list[i] = my_list[i + L + start]
my_list[i + L + start] = temp

print("List after Exchange of Elements:", my_list)

# Main program for list manipulation


def main():
rep = 'y'
print("Program for List Manipulation")

while [Link]() == 'y':


print("1. Exchange List Elements")
print("2. Count the Number of Palindromes")

ch = int(input("Enter the Choice: "))

if ch == 1:
my_list = list(eval(input("Enter the list of Numbers: ")))
half_and_half(my_list)
elif ch == 2:
count = 0
list_of_str = list(eval(input("Enter the List of Strings: ")))

for i in list_of_str:
if i == i[::-1]:
count += 1

print("The Number of Palindromes are", count)

rep = input("Do you want to continue? (y/n): ")

if __name__ == "__main__":
main()

__________________________________________________

You might also like