· 6 years ago · Sep 22, 2019, 06:52 PM
111. ANAGRAM STRING
2
3def check(s1, s2):
4
5 # the sorted strings are checked
6 if(sorted(s1)== sorted(s2)):
7 print("The strings are anagrams.")
8 else:
9 print("The strings aren't anagrams.")
10
11# driver code
12s1 ="listen"
13s2 ="silent"
14check(s1, s2)
15
1612.
17
18huge_list = []
19with open(huge_file, "r") as f:
20 for line in f:
21 huge_list.extend(line.split())
22print(huge_list)
23
24OR
25
26huge_list = []
27with open(huge_file, "r") as f:
28 huge_list = f.read().split()
29print(huge_list)
30
31
32
33
34
3515. READ FIRST N LINES OF A FILE
36
37def file_read_from_head(fname, nlines):
38 from itertools import islice
39 with open(fname) as f:
40 for line in islice(f, nlines):
41 print(line)
42file_read_from_head('test.txt',2)
43
44
45
46
47
48
4916. READ LAST N LINES OF A FILE
50
51def read_last_lines(filename, no_of_lines=1):
52 file = open(filename,'r')
53 lines = file.readlines()
54 last_lines = lines[-no_of_lines:]
55 for line in last_lines:
56 print(line)
57 file.close()
58
59
60if __name__ == "__main__":
61 filename = "file.txt"
62 read_last_lines(filename,2)
63
64OR
65
66f=file1.readlines()
67last=&[-3:]
68for I in last :
69 print(i)
70file1.close()
71
72
73
74
75
76
7717. READ FILE LINE BY LINE AND STORE IT INTO A LIST.
78
79def file_read(fname):
80 with open(fname) as f: #Content_list is the list that contains the read lines.
81 content_list = f.readlines()
82 print(content_list)
83file_read(\'test.txt\')
84
85
86
87
88
8918. PROGRAM TO FIND THE LONGEST WORDS IN A FILE
90
91def longest_word(filename):
92with open(filename, 'r') as infile:
93words = infile.read().split()
94max_len = len(max(words, key=len))
95return [word for word in words if len(word) == max_len] print(longest_word('test.txt'))
96
97
98
99
100
10119. FREQUENCY OF WORDS IN A FILE
102
103from collections import Counter
104def word_count(fname):
105 with open(fname) as f:
106 return Counter(f.read().split())
107print("Number of words in the file :",word_count("test.txt"))
108
109
110
111
112
11320. Python program to combine each line from first file with the corresponding line in second file.
114with open('abc.txt') as fh1, open('test.txt') as fh2:
115for line1, line2 in zip(fh1, fh2): # line1 from abc.txt, line2 from test.txtg
116print(line1+line2)
117
118
119
12021.
121
122import random
123
124def random_line(fname):
125
126 lines = open(fname).read().splitlines()
127
128 return random.choice(lines)
129
130print(random_line('words.txt'))
131
132
133
134
13522.
136
137def remove_newlines(fname):
138
139 flist = open(fname).readlines()
140
141 return [s.rstrip('\n') for s in flist]
142
143print(remove_newlines("words.txt"))
144
145
146
14723.
148
149def find_missing(lst):
150
151 return [x for x in range(lst[0], lst[-1]+1)
152
153 if x not in lst]
154
155
156
157
158
159lst = [1, 2, 4, 6, 7, 9, 10]
160
161print(find_missing(lst))
162
163
164
165
166
16724.
168
169#queue
170
171class queue:
172
173 def __init__(self):
174
175 pass
176
177
178
179 def add(self,no,lst):
180
181 lst.append(no)
182
183 return lst
184
185
186
187 def remove(self,lst):
188
189 lst=lst.remove(lst[0])
190
191
192
193
194
195
196
197n=int(input("ENTER THE NUMBER OF ELEMENTS IN QUEUE"))
198
199ob=queue()
200
201lst=[]*n
202
203for i in range(0,n):
204
205 n1=int(input("ENTER THE ELEMENT"))
206
207 l=ob.add(n1,lst)
208
209print(l)
210
211
212
213print("REMOVED ELEMENT IS",lst[0])
214
215e=ob.remove(lst)
216
217print(l)
218
219
220
221
222
223#stack
224
225class stack:
226
227 def __init__(self):
228
229 pass
230
231
232
233 def push(self,no,lst):
234
235 lst.append(no)
236
237 return lst
238
239
240
241 def pop(self,lst):
242
243 a=lst.pop()
244
245 return a
246
247
248
249n=int(input("ENTER THE NUMBER OF ELEMENTS IN STACK"))
250
251ob=stack()
252
253lst=[]*n
254
255for i in range(0,n):
256
257 n1=int(input("ENTER THE ELEMENT"))
258
259 l=ob.push(n1,lst)
260
261print(l)
262
263
264
265e=ob.pop(lst)
266
267print("POPPED ELEEMNT IS",e)
268
269print(l)
270
271
272
273#linkedlist
274
275class linkedlist:
276
277 def __init__(self):
278
279 pass
280
281
282
283 def insert(self,n,no,lst):
284
285 pos=int(input("ENTER THE POSITION IN LIST "))
286
287 if(pos==1):
288
289 lst.insert(0,no)
290
291 elif(pos==n):
292
293 lst=lst.append(no)
294
295 else:
296
297 lst.insert(pos-1,no)
298
299
300
301
302
303 def delete(self,n,lst):
304
305 pos=int(input("ENTER THE POSITION IN LIST TO BE DELETED "))
306
307 print("DELETED ELEMENT IS ",lst[pos-1])
308
309 lst.remove(lst[pos-1])
310
311
312
313
314
315
316
317
318
319
320
321n=int(input("ENTER THE NUMBER OF ELEMENTS IN LINKED LIST "))
322
323ob=linkedlist()
324
325lst=[]*n
326
327ip=0
328
329
330
331while(ip!=4):
332
333 ip=int(input("CHOOSE AN OPTION: 1:CREATE 2.INSERT 3.DELETE 4.EXIT "))
334
335
336
337 if(ip==1):
338
339 for i in range(0,n):
340
341 n1=int(input("ENTER THE ELEMENT "))
342
343 lst.append(n1)
344
345 print("LINKED LIST IS ",lst)
346
347
348
349 if(ip==2):
350
351 n1=int(input("ENTER THE ELEMENT TO BE INSERTED "))
352
353 ob.insert(n,n1,lst)
354
355 print(lst)
356
357
358
359 if(ip==3):
360
361 ob.delete(n,lst)
362
363 print(lst)
364
365
366
367'''
368
369'''
370
371
372
373
37425.
375
376class py_solution:
377
378 def reverse_words(self, s):
379
380 return ' '.join(reversed(s.split()))
381
382
383
384
385
386print(py_solution().reverse_words('i am tanuja'))
387
388
389
390
391
392
393
39426.
395
396fn = open('words.txt', 'r')
397
398fn1 = open('new.txt', 'w')
399
400
401
402cont = fn.readlines()
403
404for i in range(0, len(cont)):
405
406 if(i % 2!=0):
407
408 fn1.write(cont[i])
409
410 else:
411
412 pass
413
414
415
416fn1.close()
417
418fn1 = open('new.txt', 'r')
419
420cont1 = fn1.read()
421
422print(cont1)
423
424fn.close()
425
426fn1.close()
427
428
429
430
431
43227.
433
434class py_solution:
435
436 def sub_sets(self, sset):
437
438 return self.subsetsRecur([], sorted(sset))
439
440
441
442 def subsetsRecur(self, current, sset):
443
444 if sset:
445
446 return self.subsetsRecur(current, sset[1:]) + self.subsetsRecur(current + [sset[0]], sset[1:])
447
448 return [current]
449
450
451
452print(py_solution().sub_sets([4,5,6]))
453
454
455
456
457
45828.
459
460'''Write a program that takes a birthday as input and prints the user’s age and
461the number of days, hours, minutes and seconds until their next birthday.
462Use Class'''
463
464import datetime
465from datetime import *
466
467class Bdate():
468 birthday =date.today()
469 days_in_year=0.0
470 def __init__(self,bir):
471 self.birthDate=bir
472 self.days_in_year = 365.2425
473
474 def ageFind(self):
475 age = int((date.today() - self.birthDate).days / self.days_in_year)
476 print("Your age is ",age,"Years")
477
478 def nexBday(self,day,month,year):
479 '''nextbday=date(year,month,day)
480 no_of_days = nextbday-date.today()
481 print("no of days left for next birthday : " ,no_of_days.days)'''
482 old_time = datetime.now()
483 dt_string = old_time.strftime("%H:%M:%S")
484 dt_string1 = old_time.strftime("%d-%m-%y")
485 dt = dt_string.split(':')
486 dt1 = dt_string1.split('-')
487 dt1[2]="20" + dt1[2]
488 old=datetime(int(dt1[2]), int(dt1[1]),int(dt1[0]),int(dt[0]),int(dt[1]),int(dt[2]))
489 new = datetime(year,month,day,12,00,00)
490 diff=new-old
491 print(diff)
492
493
494
495
496
497day=int(input("Enter Birthday : "))
498month=int(input("Enter Birth Month : "))
499year = int(input("Enter Birth Year : "))
500bd = Bdate(date(year,month,day))
501bd.ageFind()
502bd.nexBday(day,month,date.today().year+1)
503
504
505
506
507
508
509
510
51129.
512
513def string_test(s):
514
515 d={"UPPER_CASE":0, "LOWER_CASE":0}
516
517 for c in s:
518
519 if c.isupper():
520
521 d["UPPER_CASE"]+=1
522
523 elif c.islower():
524
525 d["LOWER_CASE"]+=1
526
527 else:
528
529 pass
530
531 print ("Original String : ", s)
532
533 print ("No. of Upper case characters : ", d["UPPER_CASE"])
534
535 print ("No. of Lower case Characters : ", d["LOWER_CASE"])
536
537
538
539string_test('The quick Brown Fox')
540
541
542
543
54430.
545
546
547
548list1 = [10, 21, 4, 45, 66, 93]
549
550
551
552for num in list1:
553
554
555
556 if num % 2 == 0:
557
558 print(num, end = " ")
559
560
561
562
563
56431.
565
566li=range(5)
567
568
569
570def sq(n):
571
572 return n*n
573
574
575
576li1=list(map(sq,li))
577
578print(li1)
579
580
581
582
583
584
585
58632.
587
588class Shape(object):
589
590 def __init__(self):
591
592 pass
593
594
595
596 def area(self):
597
598 return 0
599
600
601
602class Square(Shape):
603
604 def __init__(self, l):
605
606 Shape.__init__(self)
607
608 self.length = l
609
610
611
612 def area(self):
613
614 return self.length*self.length
615
616
617
618aSquare= Square(3)
619
620print (aSquare.area())
621
622
623
624
625
626
627
62833.
629
630def binarySearch (arr, l, r, x):
631
632
633
634 if r >= l:
635
636
637
638 mid = int(l + (r - l)/2)
639
640
641
642 if arr[mid] == x:
643
644 return mid
645
646
647
648 elif arr[mid] > x:
649
650 return binarySearch(arr, l, mid-1, x)
651
652
653
654 else:
655
656 return binarySearch(arr, mid + 1, r, x)
657
658
659
660 else:
661
662 return -1
663
664
665
666
667
668arr = [ 2, 3, 4, 10, 40 ]
669
670x = 10
671
672
673
674result = binarySearch(arr, 0, len(arr)-1, x)
675
676
677
678if result != -1:
679
680 print ("Element is present at index % d" % result)
681
682else:
683
684 print ("Element is not present in array")
685
686
687
688
689
690
691
692
693
694
695
696
697DEC TO BIN-BIN TO DEC
698
699
700from tkinter import *
701
702
703def decToBin():
704
705 resultText.delete(0,'end')
706
707 number = value.get()
708
709 binary = bin(int(number)).replace("0b","")
710
711 resultText.insert(0,binary)
712
713
714
715def binToDec():
716
717 resultText.delete(0,'end')
718
719 number = value.get()
720
721 decimal = int(number,2)
722
723 resultText.insert(0,decimal)
724
725
726
727
728root = Tk()
729
730root.geometry("350x250")
731
732
733valLabel = Label(root,text="Enter Value :")
734
735value = Entry(root)
736
737
738valLabel.grid(row=0,column=0)
739
740value.grid(row=0,column=1)
741
742
743button1 = Button(root,text="Convert into Binary",command=decToBin)
744
745button2 = Button(root,text="Convert into Decimal",command=binToDec)
746
747
748button1.grid(row=1,column=0)
749
750button2.grid(row=1,column=1)
751
752
753resultLabel = Label(root,text="Result : ")
754
755resultText = Entry(root)
756
757resultLabel.grid(row=2,column=0)
758
759resultText.grid(row=2,column=1)
760
761
762root.mainloop()
763
764
765DEC-OCT OCT - DEC
766
767from tkinter import *
768
769
770
771def decToOc():
772
773 resultText.delete(0, 'end')
774
775 number = value.get()
776
777 octal = oct(int(number)).replace('0o','')
778
779 resultText.insert(0, octal)
780
781
782def octToDec():
783
784 resultText.delete(0, 'end')
785
786 number = value.get()
787
788 decimal = int(number,8)
789
790 resultText.insert(0, decimal)
791
792
793
794root = Tk()
795
796root.geometry("350x250")
797
798
799valLabel = Label(root, text="Enter Value : ")
800
801value = Entry(root)
802
803valLabel.grid(row=0,column=0)
804value.grid(row=0,column=1)
805
806
807button1 = Button(root, text="Decimal to Octal", command=decToOc)
808
809button2 = Button(root, text="Octal to Decimal", command=octToDec)
810button1.grid(row=1,column=0)
811
812button2.grid(row=1,column=1)
813
814
815resultLabel = Label(root, text="Result : ")
816
817resultText = Entry(root)
818
819resultLabel.grid(row=2,column=0)
820
821resultText.grid(row=2,column=1)
822
823
824root.mainloop()
825
826
827
828HEXA-DECI
829
830from tkinter import *
831
832
833def hexa():
834
835 resultText.delete(0, 'end')
836
837 number = value.get()
838
839 hexadecimal = hex(int(number)).replace('0x','')
840
841 resultText.insert(0, hexadecimal)
842
843
844
845def dec():
846 resultText.delete(0, 'end')
847
848 number = value.get()
849 decimal = int(number,16)
850
851 resultText.insert(0, decimal)
852
853
854
855root = Tk()
856
857root.geometry("350x200")
858
859
860valLabel = Label(root, text="Enter Value : ")
861
862value = Entry(root)
863
864valLabel.grid(row=0,column=0)
865
866value.grid(row=0,column=1)
867
868
869button1 = Button(root, text="Decimal To Hex", command=hexa)
870
871button2 = Button(root, text="Hex to Decimal", command=dec)
872
873
874button1.grid(row=1,column=0)
875
876button2.grid(row=1,column=1)
877
878
879resultLabel = Label(root, text="Result : ")
880
881resultText = Entry(root)
882
883
884resultLabel.grid(row=2,column=0)
885resultText.grid(row=2,column=1)
886
887
888root.mainloop()
889
890
891FACT LCM
892
893from tkinter import *
894
895
896
897def calc(no):
898
899 if no <= 1:
900
901 return 1
902
903 else:
904
905 return(no*calc(no-1))
906
907
908
909def factorial():
910
911 result.delete(0, 'end')
912
913 number = value.get()
914
915 n1 = int(number)
916
917 res = calc(n1)
918
919 result.insert(0, res)
920
921
922
923
924def lcm():
925
926 result.delete(0, 'end')
927
928 numArray = value.get().split(' ')
929
930 num1 = int(numArray[0])
931
932 num2 = int(numArray[1])
933
934
935 if num1 > num2 :
936
937 greater = num1
938
939 else:
940
941 greater = num2
942
943
944 while(True):
945
946 if((greater%num1 == 0) and (greater%num2 == 0)):
947
948 Lcm = greater
949
950 break
951
952 else:
953
954 greater += 1
955
956
957 result.insert(0, Lcm)
958
959
960
961
962root = Tk()
963
964root.geometry("350x150")
965label = Label(root, text="Enter Value : ")
966
967value = Entry(root)
968
969label.grid(row=0,column=0)
970
971value.grid(row=0,column=1)
972
973
974button1 = Button(root, text="Factorial", command=factorial)
975
976button2 = Button(root, text="LCM", command=lcm)
977
978
979button1.grid(row=1,column=0)
980
981button2.grid(row=1,column=1)
982
983
984resultLabel = Label(root, text="Result : ")
985result = Entry(root)
986
987resultLabel.grid(row=2,column=0)
988
989result.grid(row=2,column=1)
990
991
992
993root.mainloop()
994
995
996
997
998
999THE
1000
1001
1002from tkinter import *
1003from math import *
1004
1005window=Tk()
1006window.title("simple")
1007
1008lbl=Label(window,text="i am the and i wnt to fin the in this the")
1009lbl.grid(row=0)
1010lb=Listbox(window)
1011lb.insert(0,"display length of string")
1012lb.insert(0,"occ of the in string")
1013lb.grid(row=1)
1014
1015def show(*event):
1016 s="i am the and i wnt to fin the in this the"
1017 tb.delete(0,END)
1018 ans=lb.get(lb.curselection()[0])
1019 if(str(ans)=="display length of string"):
1020 tb.insert(0,len(s))
1021 if(str(ans)=="occ of the in string"):
1022 tb.insert(0,s.count("the"))
1023
1024lb.bind("<<ListboxSelect>>",show)
1025tb=Entry(window)
1026tb.grid(row=4)
1027window.mainloop()
1028
1029'''
1030#append
1031a="i am the"
1032lis=list(s)
1033lis.append(" ")
1034lis.append(a)
1035lis1=''.join(lis)
1036print(lis1)
1037'''
1038
1039
1040
1041ARMSTRONG fun
1042def isArmstrong (x):
1043 n = order(x)
1044 temp = x
1045 sum1 = 0
1046 while (temp!=0):
1047 r = temp%10
1048 sum1 = sum1 + power(r, n)
1049 temp = temp/10
1050
1051 # If condition satisfies
1052 return (sum1 == x)
1053
1054
1055
1056BUBBLE INSERTION
1057
1058
1059
1060def bubble(ar):
1061 n=len(ar)
1062
1063 for i in range(n):
1064 for j in range(n-i-1):
1065 if(ar[j]>ar[j+1]):
1066 temp=ar[j]
1067 ar[j]=ar[j+1]
1068 ar[j+1]=temp
1069
1070arr=[14,46,43,27,57,41,45,21,70]
1071bubble(arr)
1072print(arr)
1073
1074'''
1075# Function to do insertion sort
1076def insertionSort(arr):
1077
1078 # Traverse through 1 to len(arr)
1079 for i in range(1, len(arr)):
1080
1081 key = arr[i]
1082
1083 # Move elements of arr[0..i-1], that are
1084 # greater than key, to one position ahead
1085 # of their current position
1086 j = i-1
1087 while j >=0 and key < arr[j] :
1088 arr[j+1] = arr[j]
1089 j -= 1
1090 arr[j+1] = key
1091
1092
1093# Driver code to test above
1094arr = [12, 11, 13, 5, 6]
1095insertionSort(arr)
1096print ("Sorted array is:")
1097for i in range(len(arr)):
1098 print ("%d" %arr[i])
1099
1100
1101
1102PRIME HAPPY
1103
1104
1105
1106'''Given two .txt files that have lists of numbers in them, find the numbers that are overlapping. Prime.txt contains as a list of all prime numbers under 1000, and Happy.txt contains a list of happy numbers up to 1000.'''
1107
1108file1 = open('prime.txt','r')
1109file2 = open('Happy.txt','r')
1110
1111read1 = file1.readlines()
1112read2 = file2.readlines()
1113
1114prime = []
1115happy = []
1116overlap = []
1117
1118for i in read1 :
1119 prime.append(int(i))
1120
1121for i in read2 :
1122 happy.append(int(i))
1123
1124for elem in prime :
1125 if elem in happy :
1126 overlap.append(elem)
1127
1128print(overlap)
1129
1130file1.close()
1131file2.close()
1132
1133
1134
1135
1136REVERSE PAIR
1137
1138'''Two words are a “reverse pair” if each is the reverse of the other. Write a program
1139that finds all the reverse pairs in the word list.'''
1140
1141def find_reverse(list_words):
1142 reverse_pairs = []
1143
1144 for word in list_words :
1145 if word[::-1] in list_words :
1146 reverse_pairs.append(word+"/"+word[::-1])
1147 return reverse_pairs
1148
1149list_words = ['hello','how','are','olleh','era','nasty','freestyle']
1150print(find_reverse(list_words))
1151
1152
1153
1154
1155
1156ROTATE
1157
1158
1159
1160
1161def normalize(x, low, high):
1162 while x > high:
1163 x -= 26
1164 while x < low:
1165 x += 26
1166 return x
1167
1168
1169def rotate_word(word, amount):
1170 new_word = ''
1171 for letter in word:
1172 if letter.isupper():
1173 new_word += chr(normalize(ord(letter) + amount, 65, 90))
1174 elif not letter.isalpha():
1175 new_word += letter
1176 else:
1177 new_word += chr(normalize(ord(letter) + amount, 97, 122))
1178 return new_word
1179
1180print (rotate_word("This is a test. Don't try this @ home!", 13))
1181
1182
1183
1184
1185
1186
1187NO E
1188
1189
1190
1191'''Write a function called has_no_e that returns True if the given word doesn’t have the letter “e” in
1192it. Modify your program to print only the words that have no “e” and compute
1193the percentage of the words in the list have no “e.'''
1194
1195
1196def has_no_e(strr):
1197 if strr.count('e') > 0 :
1198 return True
1199 return False
1200
1201def getper(words, total):
1202 return (words/total)*100
1203
1204cnt=0
1205value = input("Enter String : ")
1206valSplit = value.split(' ')
1207for i in valSplit :
1208 if has_no_e(i) == False :
1209 print(i)
1210 cnt += 1
1211
1212print("% of words that not contains e : ", getper(cnt, len(valSplit)))
1213
1214
1215
1216
1217
1218
1219DATABASE
122034
1221
1222
1223'''Consider Employee table(empid, firstname,lastname,phone number,salary) .
1224Using python create the table and perform following operations: Display the
1225names (first_name, last_name) using alias name "First Name", "Last Name", Fetch
1226the names (first_name, last_name), salary, PF of all the employees (PF is
1227calculated as 12% of salary). (Insert 5 records in the table) .
1228Use exception handling'''
1229
1230import sqlite3
1231from sqlite3 import Error
1232
1233def db():
1234 try:
1235 con = sqlite3.connect("test.db")
1236 if(con):
1237 print("Connected")
1238 return con
1239 except Error as er:
1240 print(er)
1241 return None
1242
1243def createTable(con):
1244 try:
1245 curobj = con.cursor()
1246 curobj.execute("CREATE TABLE IF NOT EXISTS EMPLOYEE\
1247(empid int primary key,first_name text,last_name text,phoneno text,salary int)")
1248 con.commit()
1249 print("Table is Created Successfully")
1250 except Error:
1251 print(Error)
1252
1253def insertdata(con,eid,fname,lname,ph,sal):
1254 try:
1255 curobj = con.cursor()
1256 curobj.execute("INSERT INTO EMPLOYEE VALUES('"+str(eid)+"','"+fname+"',\
1257'"+lname+"','"+ph+"','"+str(sal)+"')")
1258 con.commit()
1259 print("Record Inserted!!")
1260 except Error:
1261 print(Error)
1262
1263def shownames(con):
1264 try:
1265 print("\n\n Display Data\n")
1266 curobj = con.cursor()
1267 x = curobj.execute("SELECT first_name as FIRSTNAME, last_name as\
1268 LASTNAME from EMPLOYEE;")
1269 for i in x:
1270 print("First Name : ",i[0])
1271 print("Last Name : ",i[1],"\n\n")
1272 except Error:
1273 print(Error)
1274
1275def salcal(con):
1276 try:
1277 print("\n\n Display PF Data\n")
1278 curobj = con.cursor()
1279 x = curobj.execute("SELECT first_name,last_name,salary\
1280 from EMPLOYEE;")
1281 for i in x:
1282 print("Name : ",i[0]," ",i[1])
1283 print("Salary : ",i[2])
1284 pf = (int(i[2])*12)/100
1285 print("PF : ",pf,"\n\n")
1286 except Error:
1287 print(Error)
1288
1289
1290ch = 3
1291con=db()
1292createTable(con)
1293while(ch<=4):
1294 print("1.Insert\n2.Display Name\n3.Calculate PF\n4.Exit")
1295 ch = int(input("Enter Your Choice : "))
1296 if(ch>4 or ch<1):
1297 print("Invalid Choice !!")
1298 continue
1299 elif(ch==1):
1300 eid=int(input("Enter Id : "))
1301 fname=input("Enter First name : ")
1302 lname=input("Enter Last Name : ")
1303 ph = input("Enter Phome No : ")
1304 sal=int(input("Enter Salary : "))
1305 insertdata(con,eid,fname,lname,ph,sal)
1306 elif(ch==2):
1307 shownames(con)
1308 elif(ch==3):
1309 salcal(con)
1310 else:
1311 print("BYE!!")
1312 break;
1313
1314con.close()
1315
1316
1317
1318
1319
1320
1321
1322
132335
1324
1325
1326
1327
1328
1329
1330'''Create table named as school(id, name, age, address, marks), primary key is
1331id, insert 5 records in the table, display all records from the table, Update
1332marks of student from 100 to 150 whose name is “Anjali”, Delete record which has
1333id=2. Display all records. Using python implement the given table operations.
1334Use exception handling
1335'''
1336import sqlite3
1337from sqlite3 import Error
1338def db():
1339 try:
1340 con=sqlite3.connect('test.db')
1341 print("Connection is estalibsed")
1342 return con
1343 except Error as er:
1344 print(er)
1345 return None
1346
1347def createTable(con):
1348 try:
1349 cursorObj=con.cursor()
1350 cursorObj.execute('''CREATE TABLE SCHOOL IF NOT EXIST
1351 (ID INT PRIMARY KEY NOT NULL,
1352 NAME TEXT NOT NULL,
1353 AGE INT NOT NULL,
1354 ADDRESS TEXT,
1355 MARKS TEXT);''')
1356 con.commit()
1357 print("Table is created Successfully")
1358 except Error as er:
1359 print(er)
1360
1361
1362def insertionData(con,sid,name,age,address,marks):
1363 try:
1364 cursorObj=con.cursor()
1365 cursorObj.execute("INSERT INTO SCHOOL \
1366 VALUES ('"+str(sid)+"','"+name+"','"+str(age)+"','"+address+"','"+str(marks)+"')");
1367 con.commit()
1368 print("Record Inserted !")
1369 except Error as er:
1370 print(er)
1371
1372def showdata(con):
1373 print("\n")
1374 print("\n")
1375 cursorObj=con.cursor()
1376 cursor = cursorObj.execute("SELECT * from SCHOOL")
1377 for row in cursor:
1378 print("ID = ", row[0])
1379 print("NAME = ", row[1])
1380 print("AGE = ",row[2])
1381 print("ADDRESS = ", row[3])
1382 print("MARKS = ", row[4], "\n","\n")
1383
1384
1385def updateData(con,name):
1386 try:
1387 cursorObj=con.cursor()
1388 cursorObj.execute("UPDATE SCHOOL set MARKS = 100 where NAME = '"+name+"'")
1389 con.commit()
1390 if(con.total_changes==0):
1391 print("No Record Found")
1392 else:
1393 print("Total number of rows updated :", con.total_changes)
1394 except Error:
1395 print(Error)
1396
1397
1398def deleteData(con,sid):
1399 try:
1400 cursorObj=con.cursor()
1401 con.execute("DELETE from COMPANY where ID = '"+sid+"';")
1402 con.commit()
1403 if(con.total_changes==0):
1404 print("No Record Found")
1405 else:
1406 print("Total number of rows deleted :", con.total_changes)
1407 except Error:
1408 print(Error)
1409
1410
1411ch = int(3)
1412#createTable()
1413con=db()
1414while(ch!=5):
1415 print("1.for insertion\n2.for update\n3.for delete\n4.for display\n5.Exit")
1416 ch = int(input("Enter Your Choice"))
1417 if(ch==1):
1418 sid=int(input("Enter ID : "))
1419 name=input("Name : ")
1420 age=int(input("Age : "))
1421 address=input("Address : ")
1422 marks = input("marks : ")
1423 insertionData(con,sid,name,age,address,marks)
1424 elif(ch==2):
1425 name=input("Enter Name : ")
1426 updateData(con,name)
1427 elif(ch==3):
1428 sid=int(input("Enter A Id you want to delete : "))
1429 deleteData(con,sid)
1430 elif(ch==4):
1431 showdata(con)
1432 else:
1433 print("bye")
1434 break
1435
1436
1437
1438
1439con.close()
1440
1441
1442
1443
1444
1445
1446
1447
1448FLASK simple codes
1449
1450Marks
1451
1452from flask import Flask, render_template, request
1453app = Flask(__name__)
1454
1455@app.route('/')
1456def student():
1457 return render_template('student.html')
1458
1459@app.route('/result',methods = ['POST', 'GET'])
1460def result():
1461 if request.method == 'POST':
1462 result = request.form
1463 return render_template("result.html",result = result)
1464
1465if __name__ == '__main__':
1466 app.run(debug = True)
1467
1468
1469
1470student.html
1471
1472<html>
1473 <body>
1474 <form action = "http://localhost:5000/result" method = "POST">
1475 <p>Name <input type = "text" name = "Name" /></p>
1476 <p>Physics <input type = "text" name = "Physics" /></p>
1477 <p>Chemistry <input type = "text" name = "chemistry" /></p>
1478 <p>Maths <input type ="text" name = "Mathematics" /></p>
1479 <p><input type = "submit" value = "submit" /></p>
1480 </form>
1481 </body>
1482</html>
1483
1484
1485result.html
1486
1487
1488<html>
1489 <body>
1490 <table border = 1>
1491 {% for key, value in result.items() %}
1492 <tr>
1493 <th> {{ key }} </th>
1494 <td> {{ value }} </td>
1495 </tr>
1496 {% endfor %}
1497 </table>
1498 </body>
1499</html>
1500
1501
1502WTForms
1503
1504
1505
1506from flask_wtf import Form
1507from wtforms import TextField, IntegerField, TextAreaField, SubmitField, RadioField,
1508 SelectField
1509
1510from wtforms import validators, ValidationError
1511
1512class ContactForm(Form):
1513 name = TextField("Name Of Student",[validators.Required("Please enter
1514 your name.")])
1515 Gender = RadioField('Gender', choices = [('M','Male'),('F','Female')])
1516 Address = TextAreaField("Address")
1517
1518 email = TextField("Email",[validators.Required("Please enter your email address."),
1519 validators.Email("Please enter your email address.")])
1520
1521 Age = IntegerField("age")
1522 language = SelectField('Languages', choices = [('cpp', 'C++'),
1523 ('py', 'Python')])
1524 submit = SubmitField("Send")
1525
1526
1527
1528
1529
1530from flask import Flask, render_template, request, flash
1531from forms import ContactForm
1532app = Flask(__name__)
1533app.secret_key = 'development key'
1534
1535@app.route('/contact', methods = ['GET', 'POST'])
1536def contact():
1537 form = ContactForm()
1538
1539 if request.method == 'POST':
1540 if form.validate() == False:
1541 flash('All fields are required.')
1542 return render_template('contact.html', form = form)
1543 else:
1544 return render_template('success.html')
1545 elif request.method == 'GET':
1546 return render_template('contact.html', form = form)
1547
1548if __name__ == '__main__':
1549 app.run(debug = True)
1550
1551
1552
1553
1554
1555
1556HTML File
1557
1558
1559<!doctype html>
1560<html>
1561 <body>
1562 <h2 style = "text-align: center;">Contact Form</h2>
1563
1564 {% for message in form.name.errors %}
1565 <div>{{ message }}</div>
1566 {% endfor %}
1567
1568 {% for message in form.email.errors %}
1569 <div>{{ message }}</div>
1570 {% endfor %}
1571
1572 <form action = "http://localhost:5000/contact" method = post>
1573 <fieldset>
1574 <legend>Contact Form</legend>
1575 {{ form.hidden_tag() }}
1576
1577 <div style = font-size:20px; font-weight:bold; margin-left:150px;>
1578 {{ form.name.label }}<br>
1579 {{ form.name }}
1580 <br>
1581
1582 {{ form.Gender.label }} {{ form.Gender }}
1583 {{ form.Address.label }}<br>
1584 {{ form.Address }}
1585 <br>
1586
1587 {{ form.email.label }}<br>
1588 {{ form.email }}
1589 <br>
1590
1591 {{ form.Age.label }}<br>
1592 {{ form.Age }}
1593 <br>
1594
1595 {{ form.language.label }}<br>
1596 {{ form.language }}
1597 <br>
1598 {{ form.submit }}
1599 </div>
1600
1601 </fieldset>
1602 </form>
1603 </body>
1604</html>
1605
1606
1607COOKIE
1608
1609SIMPLE COOKIE
1610from flask import *
1611
1612app = Flask(__name__)
1613
1614@app.route('/cookie')
1615def cookie():
1616 res = make_response("<h1>cookie is set</h1>")
1617 res.set_cookie('foo','bar')
1618 return res
1619
1620if __name__ == '__main__':
1621 app.run(debug = True)
1622
1623
1624
1625
1626
16271
1628
1629@app.route('/')
1630def index():
1631 return render_template('index.html')
1632
1633Index.html
1634
1635<html>
1636 <body>
1637 <form action = "/setcookie" method = "POST">
1638 <p><h3>Enter userID</h3></p>
1639 <p><input type = 'text' name = 'nm'/></p>
1640 <p><input type = 'submit' value = 'Login'/></p>
1641 </form>
1642 </body>
1643</html>
1644
16452
1646@app.route('/setcookie', methods = ['POST', 'GET'])
1647def setcookie():
1648 if request.method == 'POST':
1649 user = request.form['nm']
1650
1651 resp = make_response(render_template('readcookie.html'))
1652 resp.set_cookie('userID', user)
1653
1654 return resp
1655
16563
1657@app.route('/getcookie')
1658def getcookie():
1659 name = request.cookies.get('userID')
1660 return '<h1>welcome '+name+'</h1>'