· 6 years ago · Nov 20, 2019, 03:18 AM
1PROGRAM-1
2Write a program to print Fibonacci series.
3x=0
4y=1
5print(x)
6print(y)
7foriinrange(2,10):
8sum=x+y
9 x=y
10 y=sum
11print(sum)
12
13OUTPUT
140
151
161
172
183
195
208
2113
2221
2334
24
25
26PROGRAM-2
27Write a program to find the Sum of ‘n’ natural number.
28defseries(n):
29return n*(n+1)/2
30
31print(series(10))
32
33OUTPUT
3455.0
35
36
37
38PROGRAM-3
39Write a program to demonstrate switch case in python.
40a,b = input("enter 2 numbers").split(" ")
41a = int(a)
42b = int(b)
43
44op=input("select operation")
45if(op):
46 switcher={
47"+":a+b,
48"-":a-b,
49"*":a*b,
50"/":a/b
51 }
52print(“ans”,switcher.get(op,"invalid"))
53OUTPUT
54enter 2 numbers 10 20
55select operation *
56ans=200
57
58PROGRAM-4
59Write a program to demonstrateGlobal and local declaration
60a=10
61deffunc():
62 a="learning python"
63print(a)
64
65OUTPUT
66>>> a
6710
68>>>func()
69learning python
70>>>
71
72
73PROGRAM-5
74Write a program to demonstratearithmetic operators in python
75
76a=5
77b=2
78print("addition:", a+b)
79print("subtraction:", a-b)
80print("multiplication:", a*b)
81print("division:", a/b)
82print("modulo:", a%b)
83
84OUTPUT
85addition :7
86subtraction: 3
87multiplication :10
88division :2.5
89modulo :1
90
91PROGRAM-6
92Write a program to demonstrateLogical operators in python
93a=False
94b=True
95print(a or b)
96print(a and b)
97print(not b)
98
99OUTPUT
100True
101False
102False
103
104
105
106
107
108PROGRAM-7
109String matching regular expressions
110import re
111pattern=r"^[0-9]+.*"
112string="12abc"
113match=re.match(pattern,string)
114if match:
115print("yes")
116else:
117print("no")
118
119OUTPUT
120yes
121PROGRAM-8
122Write a program to extract Emails form a given string
123import re
124str="hello from kushagra@gmail.com to ise@gmail.com"
125emails=re.findall("\S+@\S+.",str)
126print(emails)
127
128OUTPUT
129['kushagra@gmail.com ', 'ise@gmail.com']
130
131PROGRAM-9
132Write a program toread and display a matrix (2D list)
133matrix=[]
134r=int(input("number of rows:"))
135c=int(input("number of columns:"))
136
137foriin range(0,c):
138matrix.append([])
139for j in range(0,r):
140 matrix[i].append(int(input()))
141
142print(*matrix,sep="\n")
143
144
145
146OUTPUT
147number of rows:2
148number of columns:3
1491
1502
1513
1524
1535
1546
155[1, 2]
156[3, 4]
157[5, 6]
158
159
160PROGRAM-10
161Write a program to merge 2 lists and remove any duplicates elements
162list1=[1,2,3,4]
163list2=[2,5,3,4,20,10,9]
164
165list1.extend(list2)
166result=[]
167foriin list1:
168ifinotin result:
169result.append(i)
170
171print(result)
172OUTPUT
173[1, 2, 3, 4, 5, 20, 10, 9]
174
175
176PROGRAM-11
177Write a program to print of odd tuples
178defoddtuple(tup1):
179return tup1[::2]
180print(oddtuple(('i','am','a','student')))
181
182
183OUTPUT
184('i', 'a')
185
186PROGRAM-12
187Write a program to print histogram of frequencies of characters occurring in a message, number of occurrences to be stored in a dictionary
188
189str="hello world"
190d={}
191foriin str:
192ifiin d:
193 d[i]=d[i]+1
194else:
195 d[i]=1
196foriin d:
197 print(i+":"+"*"*d[i])
198OUTPUT
199h:*
200e:*
201l:***
202o:**
203:*
204w:*
205r:*
206d:*
207
208PROGRAM-12
209Write a program to open a file and reads the contents line by line, raise exception IOError when any I/O error occurs else print program terminated
210
211try:
212 f1=open("file.txt","r")
213for line in f1:
214print(line)
215exceptIOError:
216print("I/O Error occured")
217else:
218print("Program terminated")
219
220OUTPUT
221hello world
222python
223exception
224handling
225Program terminated
226
227PROGRAM-13
228Write a program that creates 2 dictonaries , one stores conversion values from m to cm and the other stores values from cm to m
229
230
231m_cm={x:x*100for x in range(1,11)}
232temp=m_cm.values()
233cm_m={x:x/100for x in temp}
234print(m_cm)
235print(cm_m)
236
237OUTPUT
238{1: 100, 2: 200, 3: 300, 4: 400, 5: 500, 6: 600, 7: 700, 8: 800, 9: 900, 10: 1000}
239
240{100: 1.0, 200: 2.0, 300: 3.0, 400: 4.0, 500: 5.0, 600: 6.0, 700: 7.0, 800: 8.0,
241900: 9.0, 1000: 10.0}
242
243PROGRAM-14
244Write a program that stores sparse matrix as dictionary
245
246m=[[0,0,0,10,0],[2,0,0,0,3],[0,0,0,4,0]]
247d={}
248foriin range(0,len(m)):
249for j inrange(0,5):
250if(m[i][j]!=0):
251d.update({(i,j):m[i][j]})
252print(d)
253
254OUTPUT
255{(0, 3): 10, (1, 0): 2, (1, 4): 3, (2, 3): 4}
256
257
258
259
260
261
262
263PROGRAM-15
264Write a program to print the following pattern
265A
266AB
267…….
268ABCDE
269
270
271foriin range(1,6):
272for j in range(0,i):
273print(chr(65+j),end="")
274print()
275
276OUTPUT
277A
278AB
279ABC
280ABCD
281ABCDE
282
283
284PROGRAM-16
285Given the names and grades of a students store them in a nesterd list and print the names of the student with the second lowest grade. If there are multiple students with the same grade print in alphabetical order
286
287from operator importitemgetter
288l=[['H',20],['B',20],['V',19],['K',19],['Z',19]]
289m=min(l,key=itemgetter(1))[1]
290f=[x for x in l if x[1]!=m]
291mf=min(f,key=itemgetter(1))[1]
292out=[x for x in f if x[1]==mf]
293out.sort()
294foriin range (0,len(out)):
295print(out[i][0])
296
297OUTPUT
298B
299H
300
301
302
303
304PROGRAM-17
305Write a program to remove punctuations in a string
306
307str=input("enter a string:")
308p=['.',',',':','?','!']
309foriin p:
310 str=str.replace(i," ")
311print(str)
312
313OUTPUT
314enter a string: hello,world.python:lab!
315hello world python lab
316
317PROGRAM-18
318Consider the following list of sequences,write a procedure 'biggest' which return a key of the value with the largest no of values if there is more than one of the search entry return any one key
319
320animals={
321'a':['anaconda'],
322'b':['baboon'],
323'c':['crocodile']
324}
325animals['d']=['donkey']
326animals['d'].append('dog')
327animals['d'].append('dingo')
328
329defbiggest(d):
330 m=0
331Bkey=''
332foriin d:
333iflen(d[i])>m:
334 m=len(d[i])
335bkey=i
336returnBkey
337
338print('result: 'biggest(animals))
339
340OUTPUT
341result: d
342
343PROGRAM-19
344Write a program to demonstrate Exception Handling in python
345try:
346print(int('abc'))
347exceptValueError:
348print("caught value exception")
349try:
350print(int('abc'+10))
351exceptTypeError:
352print("caught Type error")
353
354OUTPUT
355caught value exception
356caught Type error
357
358
359PROGRAM-20
360Write a program that has a class 'Person' storing name and DOB subtract the DOB from the current date to see if they are eligible to vote
361
362classPerson:
363def__init__(self,name,dob):
364self.name=name
365self.DOB=dob
366defchk(self):
367 date=self.DOB.split("/")
368if ((2019-int(date[2]))>=18):
369print(self.name +" is eligible to vote")
370else:
371print(self.name + " is not eligible to vote")
372obj1=Person("Bob","27/2/1999")
373obj2=Person("Ram","27/5/2005")
374obj1.chk()
375obj2.chk()
376
377OUTPUT
378Bob is eligible to vote
379Ram is not eligible to vote
380
381
382
383PROGRAM-21
384Write a program to has class 'store' which keeps records of code and prices of all products display a menu of the products to the user and prompt him to enter the quantity of each item required
385
386classstore:
387def__init__(self,c,p):
388self.code=c
389self.price=p
390defdisplay(self):
391foriin range(0,len(self.code)):
392print(self.code[i]," ",self.price[i])
393defget_price(self,code):
394 x=self.code.index(code)
395returnself.price[x]
396
397obj=store([111,222,333],[100,300,500])
398print("CODE PRICE")
399obj.display()
400print("Enter code and quantity of products,enter 0 to checkout")
401bill=0
402while(1):
403 x=int(input("code:"))
404if(x==0):
405break
406 y=int(input("Quantity:"))
407 bill=bill+y*obj.get_price(x)
408print("Total bill amount=",bill)
409
410OUTPUT
411CODE PRICE
412111 100
413222 300
414333 500
415Enter code and quantity of products,enter 0 to checkout
416code:111
417Quantity:1
418code:222
419Quantity:1
420code:333
421Quantity:1
422code:0
423Total bill amount= 900
424
425PROGRA1M-22
426Write a program to demonstrate the sqlite3 database module in python
427
428import sqlite3
429conn = sqlite3.connect("library.db")
430c = conn.cursor()
431try:
432c.execute(""" CREATE TABLE Books(id INTEGER PRIMARY KEY,
433 name TEXT,
434amt INTEGER)""")
435for item in ((123,"Harry Potter",3),(34,"king",5)):
436c.execute("INSERT INTO Books VALUES(?,?,?)",item)
437
438c.execute(""" CREATE TABLE Student(sid INTEGER PRIMARY KEY,
439 sname TEXT,
440 age INTEGER)""")
441for item in((43,"BOB",20),(2241,"Tom",11)):
442c.execute("INSERT INTO Student VALUES(?,?,?)",item)
443
444except sqlite3.IntegrityError:
445print("DB already exists")
446pass
447
448while(1):
449c.execute("SELECT * FROM Books")
450 bookies =c.fetchall()
451for tuple in bookies:
452id,name, amot=tuple
453itt=("%d,%s,%d" % (id,name,amot))
454print(itt)
455c.execute("SELECT * FROM Student")
456 bookies = c.fetchall()
457for tuple in bookies:
458id,name,amot =tuple
459itt =("%d,%s,%d"%(id,name,amot))
460print(itt)
461print("WHAT DO YOU WANT TO DO \n1.Borrow 2.Donate 3.Exit")
462inp=int(input())
463ifinp==1:
464 k=int(input())
465 amt=int(input())
466c.execute("UPDATE Books SET amt = amt-(?) WHEREid=(?)",(amt,k))
467elifinp==2:
468 k=int(input())
469amty=int(input())
470c.execute("UPDATE Books SET amt = amt+(?) WHERE id=(?)",(amty,k))
471
472c.execute("DROP TABLE Books")
473c.execute("DROP TABLE Student")
474c.close()
475
476OUTPUT
47734,king,5
478123,Harry Potter,3
47943,BOB,20
4802241,Tom,11
481
482WHAT DO YOU WANT TO DO
4831.Borrow 2.Donate 3.Exit
4841
485123
4862
487
48834,king,5
489123,Harry Potter,1
49043,BOB,20
4912241,Tom,11
492
493
494PROGRAM-23
495Write a program to generate a random number, raise a user defined exception if the number is less than 0.1
496import random
497classRandomError(Exception):
498def__init__(self,val):
499self.value=val
500try:
501num=random.random()
502if(num<0.1):
503raiseRandomError(num)
504exceptRandomError as e:
505print(e.value,"is less than 0.1")
506else:
507print("%.3f" %num)
508
509
510OUTPUT
5110.023 is less than 0.1
512
513PROGRAM-24
514Write a program to deposit or withdraw money from Bank Account
515classAccount:
516def__init__(self):
517self.balance=0
518print("New Account created")
519
520defdeposit(self):
521 amount=float(input("Enter the amount to deposit"))
522self.balance+=amount
523print("New Balance = %f" %self.balance)
524
525defwithdraw(self):
526 amount=float(input("Enter the amount to withdraw"))
527if(amount>self.balance):
528print("Insufficient balance")
529else:
530self.balance-=amount
531print("New Balance = %f" %self.balance)
532defenquiry(self):
533print("Balance = %f" %self.balance)
534
535account=Account()
536account.deposit()
537account.withdraw()
538account.enquiry()
539
540OUTPUT
541New Account created
542Enter the amount to deposit 1000
543New balance = 1000
544Enter the amount to withdraw 500
545New balance = 500
546Enter the amount to withdraw 1000
547Insufficient balance
548Balance = 500
549
550
551
552
553PROGRAM-25
554Write a program to compare two date objects.
555import datetime
556d1=datetime.date(2018,5,3)
557d2=datetime.date(2018,6,1)
558print("d1 is greater than d2-",d1>d2)
559print("d1 is lesser than d2-",d1<d2)
560print("d1 is not equal to d2-",d1!=d2)
561OUTPUT
562d1 is greater than d2- False
563d1 is lesser than d2- True
564d1 is not equal to d2- True
565
566PROGRAM-26
567Write a number game program.Ask the user to enter a number.If number is greater than the number to be guessed raise valueTooLarge exception.If the number is lesser than the number to be guessed then raise valueTooSmall exception and prompt the user to enter again.Quit the program only when user enters the correct number.
568
569classsmall(Exception):
570defdisplay(self):
571print("Input too small")
572classlarge(Exception):
573defdisplay(self):
574print("Input too large")
575x=100
576while(1):
577try:
578num=int(input("Enter a number:"))
579if(num==x):
580print("Great you succeeded")
581break
582if(num<x):
583raise small
584elif(num>x):
585raise large
586
587except small as s:
588s.display()
589except large as l:
590l.display()
591
592OUTPUT
593Enter a number:150
594Input too large
595Enter a number:70
596Input too small
597Enter a number:100
598Great you succeeded
599
600PROGRAM-27
601Write a program to which infinitely prints natural numbers. Raise the StopIteration Exception after displaying the first 20 numbers and exit from the program.
602defdisplay(n):
603while(1):
604try:
605 n=n+1
606if(n==21):
607raiseStopIteration
608exceptStopIteration:
609print("caught StopIteration Exception")
610else:
611print(n,end=" ")
612i=0
613display(i)
614
615OUTPUT
6161 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
617caught StopIteration Exception
618
619PROGRAM-28
620Write a program to that overloads ‘+’ operator on class Student that has attributes names and marks:
621classstudent:
622def__init__(self,name,marks):
623self.name=name
624self.marks=marks
625defdisplay(self):
626print(self.name,self.marks)
627
628def__add__(self,s):
629 temp=student(s.name,[])
630foriin range(len(self.marks)):
631temp.marks.append(self.marks[i]+s.marks[i])
632return temp
633
634s1=student("ABC",[1,2,3])
635s2=student("ABC",[4,5,6])
636s1.display()
637s2.display()
638s3=student("",[])
639s3=s1+s2
640s3.display()
641
642
643OUTPUT
644ABC[1, 2, 3]
645ABC[4, 5, 6]
646ABC[5, 7, 9]
647
648PROGRAM-29
649Provide a program to scan argv lists by looking '-option_name' and optionvalue and stuff them into a dictionary by option_name
650
651from sys importargv
652options={}
653foriin range (1,len(argv),2):
654 options[argv[i]]=argv[i+1]
655print(options)
656
657PROGRAM-30
658Design a script that will search for *.docx from root path
659
660importos
661
662forroot,dir,filesinos.walk('/'):
663for f in files:
664iff.endswith('.docx'):
665 print(root+str(f))