You are on page 1of 42

K K Asiwal

PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

1. python prog. to find all prime numbers upto range given by user using function

def prime_test(n,PrimeNo):
#flag=0
for num in range(1,n+1):
for i in range(2,int(num/2)+1):
if(num%i==0):
break
else:
PrimeNo.append(num)

#_main_
choice='y'
while(choice=='y' or choice=='y'):
PrimeNo=[]
x=int(input('enter a number upto which, list of prime number you want to create:'))
flag=prime_test(x,PrimeNo)
print('List of Prime Number upto:',x,'is',PrimeNo)
choice=input(' press y to continue n to exit:')
if(choice!='y'):
print('Good by....')

*************************************************
enter a number upto which, list of prime number you want to create: 50
List of Prime Number upto: 50 is [1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
press y to continue n to exit: y
enter a number upto which, list of prime number you want to create: 1000
List of Prime Number upto: 1000 is [1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53,
59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163,
167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269,
271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,
389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499,
503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619,
631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751,
757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881,
883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
press y to continue n to exit: n
Good by....
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

2. Python program for random number generator that generates random numbers
between 1 and 6 (simulates a dice).

import random
def Number_gen():
counter = 0
myList = []
while (counter) < 6:
randomNumber = random.randint(1,6)
myList.append(randomNumber)
counter = counter + 1
print(myList)
Number_gen()

====================================================================
============================
Output: -
====================================================================
============================

[6, 3, 4, 1, 2, 3]
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

3. Python prog. to count the no. of 'the' and 'in' words in alphabets.txt file
def countThein():
file=open('alphabets.txt','r')
c1=c2=0
lines = file.read()
print(' ****contents of file**** ')
print(lines)
L=lines.split()
for i in L:
if i=="the" or i=='The':
c1=c1+1

if i=="in" or i=='In':
c2=c2+1
print('No.of \'the\' word in a file',c1)
print('No.of \'in\' word in a file',c2)
file.close()
#_main_
countThein()

====================================================================
Output: -
====================================================================
============================
****contents of file****
This is information to you
The given picture in gallery
School is the Place in sarang
we like to go in time
the value of x in y
The tajmahal situated in agra

No.of 'the' word in a file 4


No.of 'in' word in a file 5
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

4. Python program to count the no. of uppercase, lowercase & digit in a text file
'poem.txt'
digit=0
lower=0
upper=0
alpha=0
file=open('poem.txt','r')
msg=file.read()
for a in msg:
if a.isupper():
upper+=1
if a.islower():
lower+=1
if a.isdigit():
digit+=1
if a.isalpha():
alpha+=1
print('*'*50)
print('The content of files:\n',msg)
print('*'*50)
print('upper case alphabets in file=',upper)
print('lower case alphabets in file=',lower)
print('digits in file=',digit)
print('alphabets in file=',alpha)
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

====================================================================
Output: -
===================================================================
**************************************************
The content of files:
This was year 2015
when I was in London
A joyfull morning in LONDON
with Hourse RIDING and Swimming
make our enjoyment multiples 2222222232345
**************************************************
upper case alhabets in file= 18
lower case alhabets in file= 84
digits in file= 17
alphabets in file= 102
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

5. Python program to count the no. of lines start with either with 'A' and 'M' and display
those lines

def countAM():
c1=c2=0
file=open('delhi.txt','r')
str=' '
msg=file.readlines()
for k in msg:
if(k[0]=='A' or k[0]=='a'):
c1=c1+1
if(k[0]=='M'or k[0]=='m'):
c2=c2+1
file.close()
return c1,c2
# __main__ start here
print('no of lines start with (A/a) and (M/m) are',countAM())
====================================================================
============================
Output: -
====================================================================
============================
no of lines start with (A/a) and (M/m) are (3, 2)
>>>
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

6. Python program to read text file "REPORT.txt" and write those lines that start with
'A' into another file "FINAL.txt"

file1=open('report.txt','r+')
file2=open('final.txt','w+')
str=file1.readlines()
for line in str:
if (line[0]=='a' or line[0]=='A'):
file2.write(line)
file2.seek(0)
x=' '
print('The content of source file \n',str)
print('Now the content of final file')
while x:
x=file2.readline()
print(x)
file1.close()
file2.close()
===================================================================
Output: -
===================================================================
The content of source file
['Once upon a time\n', 'a tiger frighten the people\n', 'surrounding area of jungle\n', 'A hunter
entered into jungle\n', 'a cat only catch by him\n', 'The people still afraid\n']
Now the content of final file
a tiger frighten the people
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

A hunter entered into jungle


a cat only catch by him

7. '''A binary file “STUDENT.DAT” has structure (admNo, name, per). Write a
function countrec() in Python that would read contents of the file “STUDENT.DAT” and
display the details of those students whose percentage is above 75. Also display number of
students scoring above 75%'''
import pickle
def writeFile():
store=[]
n=int(input('Enter no. of record you want to write into file:'))
for i in range(n):
admNo=int(input('Enter admNo :'))
name=input('Enter name :')
per=float(input('Enter percentage :'))
record=[admNo,name,per]
store.append(record)
with open('studentdata.dat','wb') as file:
pickle.dump(store,file)

def countrec():
count=0
file=open('Studentdata.dat','rb')
read_obj=pickle.load(file)
for i in read_obj:
if i[2]>75:
print('Student has more than 75 percentage')
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

print('Admission_no :',i[0])
print('Name :',i[1])
print('Percentage :',i[2])
count+=1
print("No. of studetns get more than 75 % marks:",count)
writeFile()
countrec()

**********Output*********
Enter no. of record you want to write into file:4
Enter admNo :101
Enter name :jeet
Enter percentage :95
Enter admNo :102
Enter name :suman
Enter percentage :74
Enter admNo :103
Enter name :seema
Enter percentage :76
Enter admNo :104
Enter name :ajay
Enter percentage :65
Student has more than 75 percentage
Admission_no : 101
Name : jeet
Percentage : 95.0
Student has more than 75 percentage
Admission_no : 103
Name : seema
Percentage : 76.0
No. of studetns get more than 75 % marks: 2
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

8. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].


i. Write a user defined function CreateFile() to input data for a record and add to Book.dat
ii. Write a function CountRec(Author) in Python which accepts the Author name as
parameter and count and return number of books by the given Author are stored in the
binary file “Book.dat”

import pickle
def CreateFile():
file=open('Book2.dat','ab')
record=[]
BookNo=int(input('Enter book No :'))
Book_Name=input('Enter book name :')
Author=input('Enter Author name :')
Price=float(input('Enter Price :'))
record=[BookNo,Book_Name,Author,Price]
pickle.dump(record,file)
file.close()
def CountRec(Aut):
file=open('Book2.dat','rb')
n=0
try:
while True:
record=pickle.load(file)
if record[2]==Aut:
n=n+1
except EOFError:
file.close()
print('No. of Books written by',Aut,':',n)
x=int(input('Enter the number of author record you want to add :'))
for i in range(x):
CreateFile()
aut=input('Enter the author name to count the number of record:')
CountRec(aut)
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

****************Output****************

Enter the number of author record you want to add :4


Enter book No :1
Enter book name :English Reader
Enter Author name :Manish Jain
Enter Price :500
Enter book No :2
Enter book name :English Grammar
Enter Author name :Rahul Sharma
Enter Price :800
Enter book No :3
Enter book name :General Knowledge Today
Enter Author name :Prabhat Roy
Enter Price :125
Enter book No :4
Enter book name :GK World
Enter Author name :Prabhat Roy
Enter Price :750
Enter the author name to count the number of record:Prabhat Roy
No. of Books written by Prabhat Roy : 2
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

9. Python prog. to search a record in binary file according to roll no.

import pickle
def writeData():
file=open('s5.dat','ab') # open binary file in append mode
rno=int(input('Enter the roll number of student:'))
name=input('Enter the name of student:')
mark=float(input('Enter the marks of student:'))
record=[rno,name,mark] # list
pickle.dump(record,file) # record to be write into binary file
print('Data is successfully inserted into file')
file.close()

def search(roll):
temp=0
file=open('s5.dat','rb')
try:
while True:
data=pickle.load(file)
if data[0]==roll:
print('Roll number is found')
temp=1
break

except EOFError:
file.close()
if temp:
print('Roll No.:',data[0])
print('Name :',data[1])
print('Marks :',data[2])
else:
print('Record of roll no. :',roll,'is not found')
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

# _main_
n=int(input('Enter the number of student :'))
for i in range(n):
print('********Student-',i+1,'*********')
writeData()
choice='y'
while(choice=='y' or choice=='Y'):
roll=int(input('Enter the roll number whose record you want to search :'))
search(roll)
choice=input('Press y to see more record or press n to exit :')

*********************Output***********************
Enter the number of student :4
********Student- 1 *********
Enter the roll number of student:101
Enter the name of student:sanjay
Enter the marks of student:96
Data is successfully inserted into file
********Student- 2 *********
Enter the roll number of student:102
Enter the name of student:manu
Enter the marks of student:96
Data is successfully inserted into file
********Student- 3 *********
Enter the roll number of student:103
Enter the name of student:deepa
Enter the marks of student:91
Data is successfully inserted into file
********Student- 4 *********
Enter the roll number of student:104
Enter the name of student:mukta
Enter the marks of student:71
Data is successfully inserted into file
Enter the roll number whose record you want to search :102
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

Roll number is found


Roll No.: 102
Name : manu
Marks : 96.0
Press y to see more record or press n to exit :y
Enter the roll number whose record you want to search :104
Roll number is found
Roll No.: 104
Name : mukta
Marks : 71.0
Press y to see more record or press n to exit :y
Enter the roll number whose record you want to search :101
Roll number is found
Roll No.: 101
Name : sanjay
Marks : 96.0
Press y to see more record or press n to exit :n
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

10. Python prog. to update a record in binary file.

import pickle
def writeBinary():
data=[]
choice='y'
while( choice=='y' or choice=='Y'):
roll_no=int(input('Enter the Roll Number of student :'))
name=input('Enter the name of student :')
marks=float(input('Enter the marks of student :'))
record=[roll_no,name,marks]
data.append(record)
choice=input('Press y to enter more record :')
file=open('stu12.dat','ab+')
pickle.dump(data,file)
print('Now data of students inserted into file')
file.close()
def update():
found=0
file=open('stu12.dat','rb+')
stu_data=pickle.load(file)
print('***Student data before updation***')
print(stu_data)
choice='y'
while(choice=='y' or choice=='Y'):
roll=int(input('Enter the roll no. of student which record you want to update
:'))
for raw in stu_data:
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

if raw[0]==roll: # As list is mutable type so we can update


the value of list
raw[1]=input('Enter new name :')
raw[2]=input('Enter new mark :')
found=1
break
else:
print('Sorry record is not found of rollno :',roll)
choice=input('Press y to update data of another student :')
if found==1:
file.seek(0) # before writing new object into file move the file pointer at
beginning in file
pickle.dump(stu_data,file) # writing new object into file student
file.seek(0) # file cursor moving to beginning as file is going to be read
again do display updates
stu_data=pickle.load(file)
print('***Student data after updation of file***')
print(stu_data)
else :
print(' No updation in file ')

#_main_ start here


print('First we create a binary file and write the record')
writeBinary()
# to update a record by roll number
update()

**********Output sample-1********
First we create a binary file and write the record
Enter the Roll Number of student :101
Enter the name of student :arun
Enter the marks of student :78
Press y to enter more record :y
Enter the Roll Number of student :102
Enter the name of student :mohan
Enter the marks of student :65
Press y to enter more record :y
Enter the Roll Number of student :103
Enter the name of student :vikash
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

Enter the marks of student :74


Press y to enter more record :y
Enter the Roll Number of student :104
Enter the name of student :mohan
Enter the marks of student :99
Press y to enter more record :n
Now data of students inserted into file
***Student data before updation***
[[101, 'karan', 85.0], [102, 'divakar', 75.0], [103, 'divya', 69.0], [104, 'rubina', 91.0]]
Enter the roll no. of student which record you want to update :101
Enter new name :karan singh
Enter new mark :98
Press y to update data of another student :y
Enter the roll no. of student which record you want to update :102
Enter new name :divakar agarwal
Enter new mark :75
Press y to update data of another student :y
Enter the roll no. of student which record you want to update :103
Enter new name :divya kumari
Enter new mark :95
Press y to update data of another student :y
Enter the roll no. of student which record you want to update :104
Enter new name :rubina dutt
Enter new mark :94
Press y to update data of another student :y
Enter the roll no. of student which record you want to update :105
Sorry record is not found of rollno : 105
Press y to update data of another student :n
***Student data after updation of file***
[[101, 'karan singh', '98'], [102, 'divakar agarwal', '75'], [103, 'divya kumari', '95'], [104, 'rubina
dutt', '94']]
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

11. # python prog. to delete the record in binary file using function

import pickle
def writeData():
file=open('s23.dat','ab')
rno=int(input('Enter the roll number of student:'))
name=input('Enter the name of student:')
mark=float(input('Enter the marks of student:'))
record=[rno,name,mark]
pickle.dump(record,file)
print('Data is successfully inserted into file')
file.close()
def delete(rn):
file1=open('s23.dat','rb')
file2=open('News23.dat','wb+')
try:
while True:
msg=pickle.load(file1)
if msg[0]!=rn:
pickle.dump(msg,file2)
except EOFError:
file1.close()

print('Record is deleted successfully :')


file2.seek(0)
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

print('***The contents of file now')


try:
while True:
data=pickle.load(file2)
print('Roll No. :',data[0])
print('Name :',data[1])
print('Marks :',data[2])
except EOFError:
file2.close()
#_main_
num=int(input('Enter the number of students:'))
for i in range(num):
print('Enter the details of student :',i+1)
writeData()
r=int(input('Enter the roll number of student which record you want to delete :'))
delete(r)
****************Output****************
Enter the number of students:3
Enter the details of student : 1
Enter the roll number of student:101
Enter the name of student:ram
Enter the marks of student:96
Data is successfully inserted into file
Enter the details of student : 2
Enter the roll number of student:102
Enter the name of student:subham
Enter the marks of student:77
Data is successfully inserted into file
Enter the details of student : 3
Enter the roll number of student:103
Enter the name of student:seema
Enter the marks of student:94
Data is successfully inserted into file
Enter the roll number of student which record you want to delete :102
Record is deleted successfully :
***The contents of file now
Roll No. : 101
Name : ram
Marks : 96.0
Roll No. : 103
Name : seema
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

Marks : 94.0

12. Python prog. to write the students details name, class, mark & grade into csv file

import csv
def student_data():
file=open('student_data.csv','w',newline='')
choice='y'
header=['Name','Class','Percentage','Grade']
writer_obj=csv.writer(file,delimiter=',')
writer_obj.writerow(header)
while(choice=='y' or choice=='Y'):
per=0
total=0
name=input('Enter name of student : ')
Class=int(input('Enter class of student(number only) : '))
for i in range(3):
print('Enter mark in subject-',i+1)
m=float(input('Enter mark : '))
total=total+m
per=round(total/3,2)
if per>90:
grade='A'
elif per>75:
grade='B'
elif per>60:
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

grade='C'
else:
grade='D'
row=[name,Class,per,grade]
writer_obj.writerow(row)
choice=input('Enter y to write data of more student into file : ')
file.close()
def display():
file=open('student_data.csv','r',newline='')
obj=csv.reader(file)
for i in obj:
print(i)
file.close()

#_main_
student_data()
display()

****************Output****************
Enter name of student : shyam
Enter class of student(number only) : 10
Enter mark in subject- 1
Enter mark : 85
Enter mark in subject- 2
Enter mark : 96
Enter mark in subject- 3
Enter mark : 74
Enter y to write data of more student into file : y
Enter name of student : mohita
Enter class of student(number only) : 11
Enter mark in subject- 1
Enter mark : 96
Enter mark in subject- 2
Enter mark : 84
Enter mark in subject- 3
Enter mark : 63
Enter y to write data of more student into file : y
Enter name of student : jyoti
Enter class of student(number only) : 12
Enter mark in subject- 1
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

Enter mark : 96
Enter mark in subject- 2
Enter mark : 71
Enter mark in subject- 3
Enter mark : 68
Enter y to write data of more student into file : n
['Name', 'Class', 'Percentage', 'Grade']
['shyam', '10', '85.0', 'B']
['mohita', '11', '81.0', 'B']
['jyoti', '12', '78.33', 'B']

13. Python prog. to create menu driven program in python to insert and search the
employee data in employee.csv file

import csv
def create_csv():
file=open('employee.csv','a',newline='')
choice='y'
header=['Name','bank','branch_name','salary']
writer_obj=csv.writer(file,delimiter=',')
writer_obj.writerow(header)
while(choice=='y' or choice=='Y'):
per=0
total=0
name=input('Enter name of employee : ')
bank=input('Enter bank name name : ')
branch=input('Enter branch name : ')
salary=float(input('Enter salary of employee : '))
row=[name,bank,branch,salary]
writer_obj.writerow(row)

choice=input('Enter y to write data of more student into file : ')


K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

file.close()
def search():
name1=input('Enter name of employee which record you want to search')
file=open('employee.csv','r',newline='')
reader_obj=csv.reader(file,delimiter=',')
for row in reader_obj:
if row[0]==name1:
print('Search is successul')
print('Employee Name :',row[0])
print('Employee work in :',row[1])
print('Employee branch is :',row[2])
print('Employee Salary is :',row[3])
break;
else:
print('Employee data is not found')
file.close()

def displayAll():
file=open('employee.csv','r',newline='')
reader_obj=csv.reader(file,delimiter=',')
next(reader_obj)
for row in reader_obj:
print('*****************Employee Details****************')
print('Employee Name :',row[0])
print('Employee work in :',row[1])
print('Employee branch is :',row[2])
print('Employee Salary is :',row[3])
print('******************************************************')
file.close()

#_main_
while True:
print('******************************************************')
print('Press 1 to enter details of employee :')
print('Press 2 to search the employee data :')
print('Press 3 to see the details of all employee :')
print('Press 4 to exit :')
print('******************************************************')
ch=int(input('Enter your choice(1 to 3) :'))
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

print('******************************************************')
if(ch==1):
create_csv()
elif(ch==2):
search()
elif(ch==3):
displayAll()
elif(ch==4):
break
else:
print('wrong input :')

Output :
******************************************************
Press 1 to enter details of employee :
Press 2 to search the employee data :
Press 3 to see the details of all employee :
Press 4 to exit :
******************************************************
Enter your choice(1 to 3) :3
******************************************************
*****************Employee Details****************
Employee Name : vijay singh
Employee work in : hdfc
Employee branch is : dhenkanal
Employee Salary is : 125000.0
******************************************************
******************************************************
Press 1 to enter details of employee :
Press 2 to search the employee data :
Press 3 to see the details of all employee :
Press 4 to exit :
******************************************************
Enter your choice(1 to 3) :1
******************************************************
Enter name of employee : ajay lal
Enter bank name name : ubi
Enter branch name : talcher
Enter salary of employee : 75000
Enter y to write data of more student into file : n
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

******************************************************
Press 1 to enter details of employee :
Press 2 to search the employee data :
Press 3 to see the details of all employee :
Press 4 to exit :

******************************************************
Enter your choice(1 to 3) :2
******************************************************
Enter name of employee which record you want to searchvijay singh
Search is successul
Employee Name : vijay
Employee work in : hdfc
Employee branch is : dhenkanal
Employee Salary is : 125000.0
******************************************************
Press 1 to enter details of employee :
Press 2 to search the employee data :
Press 3 to see the details of all employee :
Press 4 to exit :
******************************************************
Enter your choice(1 to 3) :3
******************************************************

*****************Employee Details****************
Employee Name : vijay singh
Employee work in : hdfc
Employee branch is : dhenkanal
Employee Salary is : 125000.0
******************************************************
*****************Employee Details****************
Employee Name : Name
Employee work in : bank
Employee branch is : branch_name
Employee Salary is : salary
******************************************************
*****************Employee Details****************
Employee Name : ajay lal
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

Employee work in : ubi


Employee branch is : talcher
Employee Salary is : 75000.0
******************************************************
******************************************************
Press 1 to enter details of employee :
Press 2 to search the employee data :
Press 3 to see the details of all employee :
Press 4 to exit :
******************************************************
Enter your choice(1 to 3) :4
******************************************************

14. Python program for Insertion in array using bisect module.

import bisect
L1=eval(input('Enter any sorted List :'))
print("Now List is Sorted :",L1)
item=int(input('Enter new element to be inserted :'))
pos=bisect.bisect(L1,item)
bisect.insort(L1,item)
print(item,"inserted at index",pos)
print('The list after inserting element')
print(L1)
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

====================================================================
============================
Output: -
====================================================================
============================
Enter any sorted List [10,20,30,50,70,80,90,150]
Now List is Sorted : [10, 20, 30, 50, 70, 80, 90, 150]
Enter new element to be inserted :25
25 inserted at index 2
The list after inserting element
[10, 20, 25, 30, 50, 70, 80, 90, 150]

15. Python prog. to searching an element in array(List) using binary search technique.

def binarySearch(arr,item):
start=0
end=len(arr)-1
while(start<=end):
mid=int((start+end)/2)
if item==arr[mid]:
return mid
elif item<arr[mid]:
end=mid-1
else:
start=mid+1
else:
return False

#_main_
n=int(input('Enter the size of list : '))
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

arr=[]
print(' *** Enter all the values in ascending order ***')
for i in range(n):
a=int(input('Enter element ['+str(i) +'] :'))
arr.append(a)
print('Now List is :',arr)
val=int(input('Enter item which you want to search in array :'))
index=binarySearch(arr,val)
if index is False:
print('Item is not found in list')
else:
print('Item is found in list at position :',index+1)
Enter the size of list : 10
*** Enter all the values in ascending order ***
Enter element [0] :4
Enter element [1] :5
Enter element [2] :18
Enter element [3] :35
Enter element [4] :39
Enter element [5] :65
Enter element [6] :69
Enter element [7] :76
Enter element [8] :97
Enter element [9] :120
Now List is : [4, 5, 18, 35, 39, 65, 69, 76, 97, 120]
Enter item which you want to search in array :97
Item is found in list at position : 9
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

16. Python program to implement stack using list

def push(stk,item):
stk.append(item)
top=len(stk)-1
def pop(stk):
if stk==[]:
print("Underflow")
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def display(stk):
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

if stk==[]:
print("stack is empty")
else:
top=len(stk)-1
for a in range(top,-1,-1):
print(stk[a],'<--',end=' ')
#____main_____
stack=[]
top=None

while True:
print("stack operations")
print("1.Push")
print("2.Pop")
print("3.Display")
print("4.Exit")
ch=int(input("Enter your choice(1-4)"))
if ch==1:
item=int(input("Enter item :"))
push(stack,item)
elif ch==2:
item=pop(stack)
print("Item deleted is:", item)
elif ch==3:
display(stack)
elif ch==4:
break
else:
print('Invalid Choice')

=================
Output: -
=================
stack operations
1.Push
2.Pop
3.Display
4.Exit
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

Enter your choice(1-4)1


Enter item :10
stack operations
1.Push
2.Pop
3.Display
4.Exit
Enter your choice(1-4)1
Enter item :20
stack operations
1.Push
2.Pop
3.Display
4.Exit
Enter your choice(1-4)1
Enter item :30
stack operations
1.Push
2.Pop
3.Display
4.Exit
Enter your choice(1-4)3
30 <-- 20 <-- 10 <-- stack operations
1.Push
2.Pop
3.Display
4.Exit
Enter your choice(1-4)2
Item deleted is: 30
stack operations
1.Push
2.Pop
3.Display
4.Exit
Enter your choice(1-4)3
20 <-- 10 <-- stack operations
1.Push
2.Pop
3.Display
4.Exit
Enter your choice(1-4)
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

17. '''Small Python program that sends a SQL query to a database and displays the result
from table student store in database.
1) To show all information about the students of History department.
2) To list the names of female students who are in Hindi department.
3) To list name of student start with s.
4) write output of following Sql query :
i) Select department, count(*) from student group by department;
ii) Select name where between 25 and 30;
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

'''
import mysql.connector as m
mycon=m.connect(host='localhost',user='root',passwd='kka',database='mysql')
if mycon.is_connected():
print('Successfully connected')
mycursor=mycon.cursor()
sql1="select * from student where department='history'"
mycursor.execute(sql1)
data=mycursor.fetchall()
print('***Query-1 output***')
for i in data:
print(i)
sql2="select name from student where department='hindi'"
mycursor.execute(sql2)
data=mycursor.fetchall()
print('***Query-2 output***')
for i in data:
print(i)
sql3="select name from student where name like 's%'"
mycursor.execute(sql3)
data=mycursor.fetchall()
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

print('***Query-3 output***')
for i in data:
print(i)
====================================================================
Output: -
====================================================================
Successfully connected
***Query-1 output***
('shalini', 21, 'history', datetime.date(1998, 3, 24), 200.0, 'F')
('sudha', 25, 'history', datetime.date(1999, 7, 1), 400.0, 'F')
('shakeel', 30, 'history', datetime.date(1998, 6, 27), 300.0, 'M')
***Query-2 output***
('rakesh',)
('shikha',)
('sanjay',)
***Query-3 output***
('shalini',)
('sudha',)
('shakeel',)
('surya',)
('shikha',)
('sanjay',)

18. '''Small Python program that sends a SQL query to a database and displays the result
from table student store in database.
1) To count the no of male and female student.
2) To display no. of students department wise.
3) To display name and age of female student of Hindi department.
4) Write output of following Sql query :
i) Select name, dateofadm from student where sex=’F’;
ii) Select sum(fee) where sex=’M’
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

'''
import mysql.connector as m
mycon=m.connect(host='localhost',user='root',passwd='kka',database='mysql')
if mycon.is_connected():
print('Successfully connected')
mycursor=mycon.cursor()
sql1="select sex, count(*) from student group by sex"
mycursor.execute(sql1)
data=mycursor.fetchall()
print('***Query-1 output***')
for i in data:
print(i)
sql2="select department,count(*) from student group by department"
mycursor.execute(sql2)
data=mycursor.fetchall()
print('***Query-2 output***')
for i in data:
print(i)
sql3="select name,age from student where department='hindi' and sex='f'"
mycursor.execute(sql3)
data=mycursor.fetchall()
print('***Query-3 output***')
for i in data:
print(i)

====================================================================
============================
Output: -
====================================================================
============================
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

Successfully connected
***Query-1 output***
('F', 3)
('M', 5)
***Query-2 output***
('computer', 2)
('hindi', 3)
('history', 3)
***Query-3 output***
('shikha', 23)

19. Small Python program that sends a SQL query to a database and displays the result
from table garment store in database.
1) To display garment name and price in ascending order of price.
2) To display garment name, color and size from table garment.
3) To increment the price of ladies top by 250.
4) Write output of following Sql query :
i) Select gcode, gname from garment where price<1500;
ii) Select gname,size from garment where colour=’Blue’;
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

'''

import mysql.connector as m
mycon=m.connect(host='localhost',user='root',passwd='kka',database='mysql')
if mycon.is_connected():
print('Successfully connected')
mycursor=mycon.cursor()
sql1="select gname,price from garment order by price"
mycursor.execute(sql1)
data=mycursor.fetchall()
print('***Query-1 output***')
for i in data:
print(i)
sql2="select gname,colour,size from garment"
mycursor.execute(sql2)
data=mycursor.fetchall()
print('***Query-2 output***')
for i in data:
print(i)
sql3="update garment set price=price+250 where gname='Ladies Top'"
mycursor.execute(sql3)
mycon.commit()
mycursor.execute("select * from garment where gname='Ladies Top'")
data=mycursor.fetchall()
print('Updated row is :')
print(data)

====================================================================
============================
Output: -
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

====================================================================
============================
Successfully connected
***Query-1 output***
('Skirt', Decimal('1100'))
('Ladies Top', Decimal('1200'))
('Tshirt', Decimal('1400'))
('Trouser', Decimal('1500'))
('Jeans', Decimal('1600'))
('Ladies Jacket', Decimal('4000'))
***Query-2 output***
('Tshirt', 'Red', 'XL')
('Jeans', 'Blue', 'L')
('Skirt', 'Black', 'M')
('Ladies Jacket', 'Blue', 'XL')
('Trouser', 'Brown', 'L')
('Ladies Top', 'orange', ' L')
Updated row is :
[(116, 'Ladies Top', ' L', 'orange', Decimal('1450'))]

20. Small Python program that sends a SQL query to a database and displays the result
from table Library store in database.
1) To display all the details of McGraw publisher from table library.
2) To display title and author name of all programming books.
3) To display book title with total value, calculate as qty*price.
4) Write output of following Sql query:
i) Select max(price) from Library;
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

ii) Select author, pub from Library where price between 500 and 1000;

import mysql.connector as m
mycon=m.connect(host='localhost',user='root',passwd='kka',database='mysql')
if mycon.is_connected():
print('Successfully connected')
mycursor=mycon.cursor()
sql1="select * from library where pub='McGraw'"
mycursor.execute(sql1)
data=mycursor.fetchall()
print('***Query-1 output***')
for i in data:
print(i)
sql2="select title,author from library where type='PROG'"
mycursor.execute(sql2)
data=mycursor.fetchall()
print('***Query-2 output***')
for i in data:
print(i)
sql3='select title, qty*price from library'
mycursor.execute(sql3)
data=mycursor.fetchall()
print('***Query-3 output***')
for i in data:
print(i)
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

====================================================================
============================
Output: -
====================================================================
============================
Successfully connected
***Query-1 output***
(1, 'Data Structure', 'Lipschutz', 'DS', 'McGraw', 5, 650.0)
(2, 'Pascal', 'Schildt', 'PROG', 'McGraw', 2, 350.0)
***Query-2 output***
('Pascal', 'Schildt')
('Mastering C++', 'Gurewich')
('Basic', 'Morton')
***Query-3 output***
('Data Structure', 3250.0)
('Pascal', 700.0)
('Dbase', 3000.0)
('Mastering C++', 3000.0)
('Basic', 300.0)
('DOS Guide', 1845.0)
('Network', 6125.0)

21. '''Small Python program that sends a SQL query to a database and displays the result
from table Library store in database.
1) To display no. of books in each type .
2) To display title of books whose prices are between 500 and 800.
3) To maximum price of books by each publisher.
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

4) Write output of following Sql query :


i) Select author from Library where author like ‘%to%’;
ii) select type,count(type) from Library group by type ;

import mysql.connector as m
mycon=m.connect(host='localhost',user='root',passwd='kka',database='mysql')
if mycon.is_connected():
print('Successfully connected')
mycursor=mycon.cursor()
sql1="select type,sum(qty) from library group by type"
mycursor.execute(sql1)
data=mycursor.fetchall()
print('***Query-1 output***')
for i in data:
print(i)
sql2="select title from library where price between 500 and 800"
mycursor.execute(sql2)
data=mycursor.fetchall()
print('***Query-2 output***')
for i in data:
print(i)
sql3='select pub,max(price) from library group by pub'
mycursor.execute(sql3)
data=mycursor.fetchall()
print('***Query-3 output***')
for i in data:
print(i)
K K Asiwal
PGT Comp.Sc.
JNV Dhenkanal, Odisha
________________________________________________________________________________________________________________________

===============================================================
=================================
Output: -
====================================================================
============================
Successfully connected
***Query-1 output***
('DBMS', Decimal('3'))
('DS', Decimal('5'))
('NT', Decimal('7'))
('OS', Decimal('9'))
('PROG', Decimal('23'))
***Query-2 output***
('Data Structure',)
('Mastering C++',)
***Query-3 output***
('BPB', 500.0)
('Galgotia', 875.0)
('McGraw', 650.0)
('PHI', 205.0)
('Pustak', 1000.0)

You might also like