· 6 years ago · Sep 22, 2019, 03:24 PM
1#read 1st line
2#def file_read_from_head(fname, nlines):
3
4 # from itertools import islice
5 # with open(fname) as f:
6 # for line in islice(f, nlines):
7 # print(line)
8#file_read_from_head('test.txt',2)
9
10#display in list
11#def file_read(fname):
12 # with open(fname) as f:
13 # #Content_list is the list that contains the read lines.
14 # content_list = f.readlines()
15 # print(content_list)
16#file_read(\'test.txt\')
17
18#longest
19#def longest_word(filename):
20 # with open(filename, 'r') as infile:
21 # words = infile.read().split()
22 # max_len = len(max(words, key=len))
23 #return [word for word in words if len(word) == max_len]
24
25#print(longest_word('test.txt'))
26
27#frequency
28#from collections import Counter
29#def word_count(fname):
30 # with open(fname) as f:
31 # return Counter(f.read().split())
32#print("Number of words in the file :",word_count("test.txt"))
33
34#random
35
36#import random
37#def random_line(fname):
38 # lines = open(fname).read().splitlines()
39 # return random.choice(lines)
40#print(random_line('test.txt'))
41
42#remove newline char
43
44#def remove_newlines(fname):
45 # flist = open(fname).readlines()
46 # return [s.rstrip('\n') for s in flist]
47#print(remove_newlines("test.txt"))
48
49#missing num
50#def find_missing(lst):
51 #return [x for x in range(lst[0], lst[-1]+1)
52 # if x not in lst]
53#lst = [1, 2, 4, 6, 7, 9, 10]
54#print(find_missing(lst))
55
56
57#def reverseWords(input):
58 #words = input.split(" ")
59 #words=words[-1::-1]
60 #output = ' '.join(words)
61 #return output
62
63#if __name__ == "__main__":
64 # input = 'hello code hii'
65 # print(reverseWords(input))
66
67#ODD LINES
68
69#f1= open('1st.txt', 'r')
70#f2= open('2nd.txt', 'w')
71
72#cont = f1.readlines()
73#type(cont)
74#for i in range(0, len(cont)):
75 #if(i%2!=0):
76 #f2.write(cont[i])
77 #else:
78 # pass
79#f2.close()
80#f2= open('2nd.txt', 'r')
81#cont1 = f2.read()
82#print(cont1)
83
84#f1.close()
85#f2.close()
86------------------------------------------------------------
87ANAGRAM STRING
88
89def check(s1, s2):
90
91 # the sorted strings are checked
92 if(sorted(s1)== sorted(s2)):
93 print("The strings are anagrams.")
94 else:
95 print("The strings aren't anagrams.")
96
97# driver code
98s1 ="listen"
99s2 ="silent"
100check(s1, s2)
101------------
102huge_list = []
103with open(huge_file, "r") as f:
104 for line in f:
105 huge_list.extend(line.split())
106print(huge_list)
107
108OR
109
110huge_list = []
111with open(huge_file, "r") as f:
112 huge_list = f.read().split()
113print(huge_list)
114---------------------
115BIRTHDAY
116'''Write a program that takes a birthday as input and prints the user’s age and
117the number of days, hours, minutes and seconds until their next birthday.
118Use Class'''
119
120import datetime
121from datetime import *
122
123class Bdate():
124 birthday =date.today()
125 days_in_year=0.0
126 def __init__(self,bir):
127 self.birthDate=bir
128 self.days_in_year = 365.2425
129
130 def ageFind(self):
131 age = int((date.today() - self.birthDate).days / self.days_in_year)
132 print("Your age is ",age,"Years")
133
134 def nexBday(self,day,month,year):
135 '''nextbday=date(year,month,day)
136 no_of_days = nextbday-date.today()
137 print("no of days left for next birthday : " ,no_of_days.days)'''
138 old_time = datetime.now()
139 dt_string = old_time.strftime("%H:%M:%S")
140 dt_string1 = old_time.strftime("%d-%m-%y")
141 dt = dt_string.split(':')
142 dt1 = dt_string1.split('-')
143 dt1[2]="20" + dt1[2]
144 old=datetime(int(dt1[2]), int(dt1[1]),int(dt1[0]),int(dt[0]),int(dt[1]),int(dt[2]))
145 new = datetime(year,month,day,12,00,00)
146 diff=new-old
147 print(diff)
148
149day=int(input("Enter Birthday : "))
150month=int(input("Enter Birth Month : "))
151year = int(input("Enter Birth Year : "))
152bd = Bdate(date(year,month,day))
153bd.ageFind()
154bd.nexBday(day,month,date.today().year+1)
155--------------------------------------
156LCM FACT
157window=Tk()
158
159def factorial():
160 num=int(numberEntry.get())
161 fact=1
162 for i in range(1,num+1):
163 fact=fact*i
164
165 result.config(text=f"Factorial is : {fact}")
166
167
168def lcm():
169 num1=int(numberEntry.get())
170 num2=int(numberEntry2.get())
171 if num1>num2:
172 greater=num1
173 else:
174 greater=num2
175
176 lcm=0
177 while(True):
178 if greater%num1==0 and greater%num2==0:
179 lcm=greater
180 break
181 greater+=1
182
183 result.config(text=f"LCM is : {lcm}")
184
185number=Label(window,text="Enter a number : ",font=("Arial",16,"bold"))
186number.place(x=50,y=100)
187
188numberEntry=Entry(window)
189numberEntry.place(x=300,y=100)
190
191number2=Label(window,text="Enter second number : ",font=("Arial",16,"bold"))
192number2.place(x=50,y=200)
193
194numberEntry2=Entry(window)
195numberEntry2.place(x=300,y=200)
196
197b=Button(text="Factorial Recursion",command=factorial)
198b.place(x=100,y=300)
199
200b1=Button(text="LCM",command=lcm)
201b1.place(x=300,y=300)
202
203result=Label(window)
204result.place(x=200,y=400)
205
206window.geometry('500x500')
207window.mainloop()
208------------------------------
209BUBBLE INSERT
210
211from tkinter import Label,Entry,Button,Tk
212
213window=Tk()
214
215def bubble_sort():
216 s=numberEntry.get()
217 l=s.split(" ")
218 l=list(map(int, l))
219 for i in range(0,len(l)):
220 for j in range(0,len(l)-i-1):
221 if l[j]>l[j+1]:
222 l[j],l[j+1]=l[j+1],l[j]
223
224 result.config(text=f" Sorted elements : {l}")
225
226def insertion_sort():
227 s=numberEntry.get()
228 l=s.split(" ")
229 l=list(map(int, l))
230 for i in range(1,len(l)):
231 print(i)
232 j=i-1
233 pos=i
234 val=l[i]
235 while j>=0:
236 if l[j]>val:
237 l[j],l[pos]=l[pos],l[j]
238 pos=j
239 j-=1
240 print(l)
241 print()
242 result.config(text=f" Sorted elements : {l}")
243
244
245number=Label(window,text="Enter numbers seperated by space ",font=('Arial',16,'bold'))
246number.place(x=50,y=100)
247
248numberEntry=Entry(window)
249numberEntry.place(x=500,y=100)
250
251b=Button(text="Bubble Sort",command=bubble_sort)
252b.place(x=100,y=200)
253
254b1=Button(text="Insertion Sort",command=insertion_sort)
255b1.place(x=200,y=200)
256
257result=Label(window,font=("Arial",16,"bold"))
258result.place(x=100,y=300)
259
260window.geometry('700x500')
261window.mainloop()
262---------------------------------------------
263count E
264
265def has_no_e(s):
266 arr=s.split(" ")
267 length=len(arr)
268 count=0
269 for i in range(0,length):
270
271 if arr[i].find('e')>0:
272 count+=1
273 print("Word present with 'e' is : "+arr[i])
274
275
276 if count==0:
277 return True
278 else:
279 avg=(count/length)*100
280 print(f"{avg}% are names there with 'e' in text '{s}'")
281
282
283s=input("Enter some text : ")
284print()
285res=has_no_e(s)
286
287if res==True:
288 print(f"No 'e' in text '{s}'")
289-------------------------------------------------------
290armmmm
291
292from tkinter import Button,Label,Entry,Tk
293
294window=Tk()
295
296def armstrong():
297 num=numberEntry.get()
298 digits=len(num)
299 num=int(num)
300 temp=num
301 arm=0
302 while temp>0:
303 rem=temp%10
304 sum=1
305 for i in range(1,digits+1):
306 sum=sum*rem
307 arm=arm+sum
308
309 temp=temp//10
310
311 if num==arm:
312 result.config(text=f"{num} is Palindrome")
313 else:
314 result.config(text=f"{num} is not Palindrome")
315
316def sum_of_n():
317 num=int(numberEntry.get())
318 sum=0
319 temp=num
320 while temp>0:
321 rem=temp%10
322 sum=sum+rem
323 temp=temp//10
324
325 result.config(text=f"Sum of digits of {num} is {sum}")
326number=Label(window,text="Enter a number ",font=('Arial',16,'bold'))
327number.place(x=50,y=100)
328
329numberEntry=Entry(window)
330numberEntry.place(x=300,y=100)
331
332b=Button(text="Armstrong",command=armstrong)
333b.place(x=100,y=200)
334
335b1=Button(text="Sum of N",command=sum_of_n)
336b1.place(x=200,y=200)
337
338result=Label(window,font=("Arial",16,"bold"))
339result.place(x=100,y=300)
340
341window.geometry('500x500')
342window.mainloop()
343----------------------------------
344ARM SUM
345
346from tkinter import Tk,Label,Entry,Button
347
348window=Tk()
349def armstrong():
350
351 num = int(numberEntry.get())
352
353 sum = 0
354# find the sum of the cube of each digit
355 temp = num
356 while temp > 0:
357
358 digit = temp % 10
359 sum += digit ** 3
360 temp //= 10
361
362 if num == sum:
363 result.config(text=f"It is : armstrong")
364
365 else:
366 result.config(text=f"It is : not armstrong")
367
368
369def sum():
370 # num = 16
371 num = int(numberEntry.get())
372
373 if num < 0:
374 print("Enter a positive number")
375 else:
376 sum = 0
377
378 while(num > 0):
379 sum += num
380 num -= 1
381
382
383 result.config(text=f"SUM is : {sum}")
384
385number=Label(window,text="Enter a number : ",font=("Arial",16,"bold"))
386number.place(x=50,y=100)
387
388numberEntry=Entry(window)
389numberEntry.place(x=300,y=100)
390
391b=Button(text="ARMSTRONG",command=armstrong)
392b.place(x=100,y=300)
393
394b1=Button(text="SUM",command=sum)
395b1.place(x=300,y=300)
396
397result=Label(window)
398result.place(x=200,y=400)
399
400window.geometry('500x500')
401window.mainloop()
402--------------------------------------
403BIN DEC
404
405from tkinter import Tk,Label,Button,Entry
406
407
408window = Tk()
409
410
411def convertBinary():
412 val=(numberEntry.get())
413 res=int(val,2)
414 result.config(text="Decimal : "+res)
415
416def convertDecimal():
417 val=int(numberEntry.get())
418 res=bin(val)
419 result.config(text="Binary : "+res)
420
421txt=""
422number = Label(window, text="Enter Number ", font=("Arial", 19, "bold"))
423number.place(x=50, y=100)
424numberEntry = Entry(window)
425numberEntry.place(x=300, y=100)
426
427b = Button(text="DecimalToBinary", command=convertDecimal)
428b.place(x=100, y=300)
429
430b1 = Button(text="BinaryToDecimal", command=convertBinary)
431b1.place(x=300, y=300)
432
433
434result=Label(window,font=("Arial",19,"bold"))
435result.place(x=200,y=400)
436
437window.geometry('500x500')
438window.mainloop()
439------------------------------
440DEX HEC
441
442from tkinter import Tk,Label,Entry,Button
443
444window=Tk()
445
446def convertDecimal():
447 number=int(numberEntry.get())
448 res=hex(number)
449 result.config(text="Hexadeciaml : "+res)
450
451def converHexadecimal():
452 number=numberEntry.get()
453 res=int(number,16)
454 result.config(text=f"Decimal : {res}")
455
456number=Label(window,text="Enter a number",font=('Arial',16,'bold'))
457number.place(x=50,y=100)
458
459numberEntry=Entry(window)
460numberEntry.place(x=300,y=100)
461
462b1=Button(text="DecimalToHexadecimal",command=convertDecimal)
463b1.place(x=100,y=300)
464
465b2=Button(text="HexadeciamlToDecimal",command=converHexadecimal)
466b2.place(x=300,y=300)
467
468result=Label(window)
469result.place(x=200,y=400)
470
471window.geometry('500x500')
472window.mainloop()
473-------------------------------------
474circle
475
476class Circle:
477 radius=0
478 ar=0
479 def __init__(self,radius):
480 self.radius=radius
481 def area(self):
482 self.ar=3.14*(self.radius*self.radius)
483 def display(self):
484 print("Area of Circle : ",self.ar)
485c1=Circle(5)
486c1.area()
487c1.display()
488--------------------------------------------
489polygon
490
491class Polygon:
492 side=0
493 def __init__(self,side):
494 self.side=side
495 def getside(self,sides):
496 self.side=side
497
498class triangle(Polygon):
499 side=0
500 area=0
501 s1=0
502 s2=0
503 s3=0
504 def __init__(self,s1,s2,s3):
505 self.side=side
506 self.s1=s1
507 self.s2=s2
508 self.s3=s3
509 def area(self):
510 area=0.5*self.s1*self.s2
511 print(area)
512
513poly=Polygon(2,4,6)
514poly.area()
515-------------------------------
516rand div
517
518import random as r
519r=random.randrange(0,10)
520
521for i in range(1,r):
522 if i%5==0 and i%7==0:
523 print("divisible")
524 else:
525 print("not divisible")
526 --------------------
527time
528
529import datetime as dt
530class time:
531 hrs=0
532 min=0
533 sumhrs=0
534 sumMins=0
535 def __init__(self,hr,mn):
536 self.hrs=hr
537 self.min=mn
538 def display(self):
539 print("hrs")
540 print(self.hrs)
541 print("min")
542 print(self.min)
543 def addtime(self,hr2,min2):
544 print(self.hrs+hr2)
545 print(self.min+min2)
546 def display2(self):
547 print("added hrs")
548 print(self.hrs2)
549 print("added min")
550 print(self.min2)
551
552 '''def __init__(self,ref):
553 self.sumhrs=self.hrs+ref.hrs;
554 self.sumhrs=self.min+ref.min;
555 '''
556obj=time(1,35)
557obj.display()
558obj.addtime(1,15)
559obj.display2()
560#obj2=time(obj1)
561
562
563----------------------------
564LINkLIST
565
566class node:
567 right=None
568 item=None
569 def __init__(self,item):
570 self.item=item
571 def push(self,item,n):
572 self.right=n
573 def travers(self,n):
574 while n!=None:
575 print(n.item)
576 n=n.right
577
578val=input("Enter value : ")
579n=node(val)
580while(1):
581 print("1.push")
582 print("2.pop")
583 print("3.Traverse")
584 print("4.Exit")
585 ch=int(input("Enter your chioce : "))
586 if ch==1:
587 tmp=n
588 while tmp.right!=None:
589 tmp=tmp.right
590 valNew=input("Enter value : ")
591 newNode=node(valNew)
592 tmp.right=newNode
593 elif ch==2:
594 tmp=n
595 if tmp.right==None:
596 del(tmp.item)
597 else:
598 while tmp.right.right!=None:
599 tmp=tmp.right
600 tmp.right=None
601
602 elif ch==3:
603 n.travers(n)
604 elif ch==4:
605 break
606 else:
607 print("Invalid choice")
608
609
610val2=input("Enter value")
611n=node(item)
612n.push(val2)
613
614
615val3=input("Enter value")
616n.push(val3)
617--------------------------------------
618queue
619
620class queue:
621 def __init__(self,size):
622 self.size=size
623 self.arr=[]
624 self.front=-1
625 self.rear=-1
626 def insert(self,n1,size):
627 if(self.rear==self.size-1):
628 print("Queue is full")
629 else:
630 self.arr.append(n1)
631 self.rear=self.rear+1
632 def delete(self,size):
633 if(self.rear==-1 or self.front==self.rear):
634 print("Queue is empty")
635 else:
636 self.front=self.front+1
637 del(self.arr[0])
638 def display(self):
639 print(self.arr)
640size=int(input("Enter the queue size:"))
641d=queue(size)
642choice=0
643while(choice!=4):
644 print("1.insert")
645 print("2.delete")
646 print("3.display")
647 print("4.exit")
648 choice=int(input("Enter the Choice:"))
649
650 if(choice==1):
651 n1=int(input("Enter the Element:"))
652 d.insert(n1,size)
653 elif(choice==2):
654 d.delete(size)
655 elif(choice==3):
656 d.display()
657 else:
658 print("Invalid choice")
659 exit
660------------------------------------------------
661stack
662
663class data:
664 def __init__(self,size):
665 self.size=size
666 self.arr=[]
667 self.top=-1
668 def push(self,n1,size):
669 if(self.top==self.size-1):
670 print("stack is full")
671 else:
672 self.arr.append(n1)
673 self.top=self.top+1
674 def pop(self,size):
675 if(self.top==0):
676 print("stack is empty")
677 else:
678 del(self.arr[self.top])
679 self.top=self.top-1
680 def display(self):
681 print(self.arr)
682size=int(input("Enter the stack size:"))
683d=data(size)
684choice=0
685while(choice!=4):
686 print("1.Push")
687 print("2.pop")
688 print("3.display")
689 print("4.exit")
690 choice=int(input("Enter the Choice:"))
691
692 if(choice==1):
693 n1=int(input("Enter the Element:"))
694 d.push(n1,size)
695 elif(choice==2):
696 d.pop(size)
697 elif(choice==3):
698 d.display()
699 else:
700 print("Invalid choice")
701 exit
702---------------------------------
703lower uper count
704
705ch = str(input("Enter a string : "))
706upr=0
707lwr=0
708for i in ch:
709 j=ord(i)
710 if j<91 and j>64:
711 upr+=1
712 elif j<123 and j>96:
713 lwr+=1
714
715print("total lower case : ",lwr)
716print("TOTAL UPPERCASE : ",upr)
717-----------------------------------
718filter
719'''Write a program which can filter even numbers in a list by using filter
720function.'''
721
722def filter(ls1):
723 ls2=[]
724 print("Original list : ",ls1)
725 for i in ls1:
726 if(i%2==0):
727 ls2.append(i)
728 ls1.remove(i)
729 print("after filter lst1 : ",ls1)
730 print("even no : ",ls2)
731
732ln = int(input("Enter List Size : "))
733ls1=[]
734for i in range(0,ln):
735 ls1.append(int(input("Enter Element : ")))
736
737filter(ls1)
738----------------------------------------
739map
740
741'''Write a program which can map() to make a list whose elements are square of
742elements in a list'''
743
744ln = int(input("Enter List Size : "))
745ls1=[]
746for i in range(0,ln):
747 ls1.append(int(input("Enter Element : ")))
748
749print("Your List Is : ")
750print(ls1)
751
752def map(ls1):
753 ls2=[]
754 for i in ls1:
755 ls2.append(i*i)
756 print("Square of elements are :")
757 print(ls2)
758
759map(ls1)
760-------------------------------
761'''Define a class named Shape and its subclass Square. The Square class has an
762init function which takes a length as argument. Both classes have an area
763function which can print the area of the shape where Shape's area is 0 by
764default. Hints: To override a method in super class, we can define a method
765with the same name in the super class.'''
766
767class Shape:
768 leng=0;
769 def __init__(self):
770 self.leng=0
771
772 def area(self):
773 print("area of shape is : ",0)
774
775class Square(Shape):
776 squarelength=0
777 def __init__(self,length):
778 self.squarelength = length
779 #super().__init_()
780
781 def area(self):
782 print("area of a square is : ",self.squarelength*self.squarelength)
783
784l = int(input("Enter the length : "))
785sh = Square(l)
786sh.area()
787-------------------------------
788binary
789'''Write a binary search function which searches an item in a sorted list.
790The function should return the index of element to be searched in the list.'''
791lst=[];
792size=int(input("Enter Size Of the List : "))
793for i in range(0,size):
794 lst.append(int(input("Enter Value : ")))
795lst.sort()
796print(lst)
797
798def BinarySearch(lst,item):
799 first = 0
800 last = len(lst)-1
801 found = False
802 pos="No element found"
803 while(first<=last and not found):
804 mid = (first + last)//2
805 if lst[mid] == item :
806 found = True
807 pos=mid+1
808 else:
809 if item < lst[mid]:
810 last = mid - 1
811 else:
812 first = mid + 1
813 return pos
814
815ch=int(input("Enter What You Want to search ? "))
816print("Position : ",BinarySearch(lst,ch))
817
818-------------------------------
819DATABASE
820
821'''Consider Employee table(empid, firstname,lastname,phone number,salary) .
822Using python create the table and perform following operations: Display the
823names (first_name, last_name) using alias name "First Name", "Last Name", Fetch
824the names (first_name, last_name), salary, PF of all the employees (PF is
825calculated as 12% of salary). (Insert 5 records in the table) .
826Use exception handling'''
827
828import sqlite3
829from sqlite3 import Error
830
831def db():
832 try:
833 con = sqlite3.connect("test.db")
834 if(con):
835 print("Connected")
836 return con
837 except Error as er:
838 print(er)
839 return None
840
841def createTable(con):
842 try:
843 curobj = con.cursor()
844 curobj.execute("CREATE TABLE IF NOT EXISTS EMPLOYEE\
845(empid int primary key,first_name text,last_name text,phoneno text,salary int)")
846 con.commit()
847 print("Table is Created Successfully")
848 except Error:
849 print(Error)
850
851def insertdata(con,eid,fname,lname,ph,sal):
852 try:
853 curobj = con.cursor()
854 curobj.execute("INSERT INTO EMPLOYEE VALUES('"+str(eid)+"','"+fname+"',\
855'"+lname+"','"+ph+"','"+str(sal)+"')")
856 con.commit()
857 print("Record Inserted!!")
858 except Error:
859 print(Error)
860
861def shownames(con):
862 try:
863 print("\n\n Display Data\n")
864 curobj = con.cursor()
865 x = curobj.execute("SELECT first_name as FIRSTNAME, last_name as\
866 LASTNAME from EMPLOYEE;")
867 for i in x:
868 print("First Name : ",i[0])
869 print("Last Name : ",i[1],"\n\n")
870 except Error:
871 print(Error)
872
873def salcal(con):
874 try:
875 print("\n\n Display PF Data\n")
876 curobj = con.cursor()
877 x = curobj.execute("SELECT first_name,last_name,salary\
878 from EMPLOYEE;")
879 for i in x:
880 print("Name : ",i[0]," ",i[1])
881 print("Salary : ",i[2])
882 pf = (int(i[2])*12)/100
883 print("PF : ",pf,"\n\n")
884 except Error:
885 print(Error)
886
887
888ch = 3
889con=db()
890createTable(con)
891while(ch<=4):
892 print("1.Insert\n2.Display Name\n3.Calculate PF\n4.Exit")
893 ch = int(input("Enter Your Choice : "))
894 if(ch>4 or ch<1):
895 print("Invalid Choice !!")
896 continue
897 elif(ch==1):
898 eid=int(input("Enter Id : "))
899 fname=input("Enter First name : ")
900 lname=input("Enter Last Name : ")
901 ph = input("Enter Phome No : ")
902 sal=int(input("Enter Salary : "))
903 insertdata(con,eid,fname,lname,ph,sal)
904 elif(ch==2):
905 shownames(con)
906 elif(ch==3):
907 salcal(con)
908 else:
909 print("BYE!!")
910 break;
911
912con.close()
913-------------------------------
914'''Create table named as school(id, name, age, address, marks), primary key is
915id, insert 5 records in the table, display all records from the table, Update
916marks of student from 100 to 150 whose name is “Anjali”, Delete record which has
917id=2. Display all records. Using python implement the given table operations.
918Use exception handling
919'''
920import sqlite3
921from sqlite3 import Error
922def db():
923 try:
924 con=sqlite3.connect('test.db')
925 print("Connection is estalibsed")
926 return con
927 except Error as er:
928 print(er)
929 return None
930
931def createTable(con):
932 try:
933 cursorObj=con.cursor()
934 cursorObj.execute('''CREATE TABLE SCHOOL IF NOT EXIST
935 (ID INT PRIMARY KEY NOT NULL,
936 NAME TEXT NOT NULL,
937 AGE INT NOT NULL,
938 ADDRESS TEXT,
939 MARKS TEXT);''')
940 con.commit()
941 print("Table is created Successfully")
942 except Error as er:
943 print(er)
944
945
946def insertionData(con,sid,name,age,address,marks):
947 try:
948 cursorObj=con.cursor()
949 cursorObj.execute("INSERT INTO SCHOOL \
950 VALUES ('"+str(sid)+"','"+name+"','"+str(age)+"','"+address+"','"+str(marks)+"')");
951 con.commit()
952 print("Record Inserted !")
953 except Error as er:
954 print(er)
955
956def showdata(con):
957 print("\n")
958 print("\n")
959 cursorObj=con.cursor()
960 cursor = cursorObj.execute("SELECT * from SCHOOL")
961 for row in cursor:
962 print("ID = ", row[0])
963 print("NAME = ", row[1])
964 print("AGE = ",row[2])
965 print("ADDRESS = ", row[3])
966 print("MARKS = ", row[4], "\n","\n")
967
968
969def updateData(con,name):
970 try:
971 cursorObj=con.cursor()
972 cursorObj.execute("UPDATE SCHOOL set MARKS = 100 where NAME = '"+name+"'")
973 con.commit()
974 if(con.total_changes==0):
975 print("No Record Found")
976 else:
977 print("Total number of rows updated :", con.total_changes)
978 except Error:
979 print(Error)
980
981
982def deleteData(con,sid):
983 try:
984 cursorObj=con.cursor()
985 con.execute("DELETE from COMPANY where ID = '"+sid+"';")
986 con.commit()
987 if(con.total_changes==0):
988 print("No Record Found")
989 else:
990 print("Total number of rows deleted :", con.total_changes)
991 except Error:
992 print(Error)
993
994
995ch = int(3)
996#createTable()
997con=db()
998while(ch!=5):
999 print("1.for insertion\n2.for update\n3.for delete\n4.for display\n5.Exit")
1000 ch = int(input("Enter Your Choice"))
1001 if(ch==1):
1002 sid=int(input("Enter ID : "))
1003 name=input("Name : ")
1004 age=int(input("Age : "))
1005 address=input("Address : ")
1006 marks = input("marks : ")
1007 insertionData(con,sid,name,age,address,marks)
1008 elif(ch==2):
1009 name=input("Enter Name : ")
1010 updateData(con,name)
1011 elif(ch==3):
1012 sid=int(input("Enter A Id you want to delete : "))
1013 deleteData(con,sid)
1014 elif(ch==4):
1015 showdata(con)
1016 else:
1017 print("bye")
1018 break
1019
1020
1021
1022
1023con.close()
1024----------------------------------------------------