0% found this document useful (0 votes)
1 views32 pages

Python Lab Manual

The document is a manual for a Python programming lab that includes exercises on basic operations, control flow, data structures, file handling, and functions. It provides detailed instructions and sample programs for running Python scripts, handling errors, and performing various computations. The exercises cover topics such as calculating distances, checking even numbers, counting characters, and analyzing Fibonacci sequences.

Uploaded by

aibharadwaja
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views32 pages

Python Lab Manual

The document is a manual for a Python programming lab that includes exercises on basic operations, control flow, data structures, file handling, and functions. It provides detailed instructions and sample programs for running Python scripts, handling errors, and performing various computations. The exercises cover topics such as calculating distances, checking even numbers, counting characters, and analyzing Fibonacci sequences.

Uploaded by

aibharadwaja
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHONPROGRAMMINGLAB MANUAL

Exercise1-Basics
a)RunninginstructionsinInteractiveinterpreterandaPythonScrip
t.
[Link]:
[Link]
inyourshellorcommandprompt,thepythoninterpreterbecomesactive
witha>>>promptand waitsfor your commands.

Nowyoucantypeanyvalidpythonexpressionattheprompt.
Pythonreadsthe typed expression,evaluates it and prints the result.

[Link]:
 GotoFilemenuclickonNewFile(CTRL+N)andwritethecodeand save
[Link]
a=int(input("Enter a value "))
b=int(input("Enter b value "))
c=a+b
print("The sumis",c)
 Andrun the program by pressing F5 or RunRun Module.

Page1
PYTHONPROGRAMMINGLAB MANUAL

[Link]:
 BeforegoingtorunwehavetocheckthePATHinenvironment variables.
 Open your texteditor, type the following textand [Link].
print ("hello")

Opencommandprompt,[Link]
kesureyouchangetothedirectorywhereyousaved the filebeforedoing
it.

b)WriteaprogramtopurposefullyraiseIndentationErrorandcorre
ctit
Indentation
Codeblocksareidentifiedbyindentationratherthanusingsymbols
[Link],programsareeasiertoread.
Also,indentationclearlyidentifieswhichblockofcodeastatement
[Link],codeblockscanconsistofsinglestatements,too.
WhenoneisnewtoPython,[Link]
generallyprefertoavoidchange,soperhapsaftermanyyearsofcoding
withbracedelimitation,thefirstimpressionofusingpureindentationmay
[Link],recallthattwoofPython'sfeatures
arethatit issimplisticin natureandeasy to read.
Pythondoesnotsupportbracestoindicateblocksofcodeforclass
[Link]
[Link] indentedwith samenumberofspaces
[Link] blocks.

Page2
PYTHONPROGRAMMINGLAB MANUAL

Page3
PYTHONPROGRAMMINGLAB MANUAL

Exercise2-Operations
a)Writeaprogramtocomputedistancebetweentwopointstakinginputf
romtheuser
(PythagoreanTheorem)

Program:

b)Writeaprogramadd.pythattakes2numbersascommandlineargume
ntsandprintsitssum.

Program:
import sys
a=int([Link][1])
b=int([Link][2])
c=a+b
print("The sumis",c)

Output:

Page4
PYTHONPROGRAMMINGLAB MANUAL

Exercise-3ControlFlow
a)WriteaProgramforcheckingwhetherthegivennumberisanevennum
berornot.
Program:
a=int(input("Enter thenumber: "))
if(a%2==0):
print(a,"isEVEN")
else:
print(a,"isNOT EVEN")
Output-1:
Enter the number:15
15isNOTEVEN
Output-2:
Enter the number:24
24isEVEN
b)Usingaforloop,writeaprogramthatprintsoutthedecimalequivalent
sof1/2,1/3,1/4,...,1/10
Program:
i=1
foriinrange(1,11):
print("Decimal equivalent value for
1/",i,"is",1/float(i))Output:
Decimalequivalentvalue for 1/1 is 1.0
Decimalequivalentvalue for 1/2 is0.5
Decimalequivalentvalue for 1/3 is 0.333333333333
Decimalequivalentvalue for 1/4 is 0.25
Decimalequivalentvalue for 1/5 is 0.2
Decimalequivalentvalue for 1/6 is 0.166666666667
Decimalequivalentvalue for 1/7 is 0.142857142857
Decimalequivalentvalue for 1/8 is 0.125
Decimalequivalentvalue for 1/9 is 0.111111111111
Decimalequivalentvalue for 1/10 is0.1

c)[Link]
uence?
Sequence:
[Link]
theitemsoflists,tuples,strings,thekeysofdictionariesandother iterables.
ThePythonforloopstartswiththekeyword"for"followed byan

Page5
PYTHONPROGRAMMINGLAB MANUAL

arbitraryvariablename,whichwillholdthevaluesofthefollowing sequence
object.
for<variable>in<sequence>:<
statements>
else:
<statements>
Program:
players=["kohli", "dhoni","sachin", "sehwag","Dravid"]
foriinplayers:
print(i)O
utput:
kohlidh
onisachi
nsehwa
gDravid
d)Writeaprogramusingawhileloopthataskstheuserforanumber,andp
[Link]:
n=input("Enter thenumber forcountdown: ")
while (0<=n):
print(n)
n=n-1
Output:
Enter the number forcountdown:15
1514 1312 11 109 8 76 54 3 2 1 0

Page6
PYTHONPROGRAMMINGLAB MANUAL

Exercise-4-ControlFlow–
Continueda)Findthesumofalltheprimesbelowtwomillion
.
Program:
n=int(input("Enter therange:"))
sum=0
for num inrange(1,n+1):
fori in range(2,num):
if(num%i)== 0:
break
else:
sum += num
print("Sumofprimenumbers
is",sum)Output:
Enter the range: 100
Sumofprime numbers is1061

b)EachnewtermintheFibonaccisequenceisgeneratedbyaddingthep
revioustwoterms.Bystartingwith1and2,thefirst10termswillbe:
1,2,3,5,8,13,21,34,55,89,...
ByconsideringthetermsintheFibonaccisequencewhosevaluesdonot
exceedfourmillion,[Link]:
n=int(input("Enter n value "))
f0=1
f1=2
sum=f1
print(f0,f1)
foriinrange(1,n-1):
f2=f0+f1
printf2,
if f2%2==0:
sum+=f2
f0=f1
f1=f2
print("\nThe sumofeven Fibonacci numbers is",
sum)Output:
Enter n value 10
1 2 35 81321 34 5589
The sumof even Fibonacci numbers is 44

Page7
PYTHONPROGRAMMINGLAB MANUAL

Exercise-5-DS
a)Writeaprogramtocountthenumbersofcharactersinthestringandsto
[Link]:
list=[]
foriinrange(1,5):
a=input("Enter the string ")
[Link](a)
print("List is",list)
dict={}
foriin list:
dict[i]=len(i)
print("Dictionary is",dict)
Output:
Enter the string "WELCOME"
Enter the string "TO"
Enter the string "PYTHON"
Enter the string "LAB"
Listis['WELCOME', 'TO', 'PYTHON', 'LAB']
Dictionary is {'PYTHON': 6, 'TO': 2,'WELCOME':7,'LAB':3}

b)Writeaprogramtousesplitandjoinmethodsinthestringandtraceabir
thdaywithadictionarydatastructureProgram:
dob={"mothi":"12-11-1990","sudheer":"17-08-1991","vinay":"31-
08-1988"}
str1=input("which person dob you want: ")
l=[Link]()
birth=""
for iin l:
ifi in [Link]():
name=i
print"".join([name,"Birthday is",dob[name]])
Output:
which person dob you want:"i want mothibirthday"
mothiBirthday is12-11-1990

Page8
PYTHONPROGRAMMINGLAB MANUAL

Exercise-6DS-Continued
a)Writeaprogramcombine_liststhatcombinestheselistsintoadiction
ary.
Program:
subjects=['ENG','M1','M3','CP','PHY','CHE']
marks=[85,90,91,95,84,87]
z=zip(subjects, marks)
d=dict(z)
print d
Output:
{'CHE': 87, 'ENG': 85, 'PHY': 84, 'M1':90, 'M3':91, 'CP':95}

b)[Link]
uusecharacterfrequencytotellwhetherthegivenfileisaPythonprogra
mfile,Cprogramfileoratextfile?
Program:
filename=input("Enter the filename:")
f=open(filename, "r")
count=dict()
for line in f:
forch in line:
ifch in count:
count[ch]=count[ch]+1
else:
count[ch]=1
print count
[Link]()
Output:
{' ': 36, '-':2, ',':3,'.':3, 'E':1,'I': 1,'P':2, 'a':18, 'c':8, 'b': 3, 'e': 29,
'd':8, 'g':11, 'f':2, 'i':16, 'h': 12, 'k':1, 'j':1, 'l': 10, 'o': 11, 'n':20,
'q':1, 'p': 3, 's':16, 'r': 13, 'u':9, 't':22, 'w': 3,'v':2, 'y': 6}

Page9
PYTHONPROGRAMMINGLAB MANUAL

Exercise-7Files
a)[Link]
m:
filename=input("Enter the filename:")
f=open(filename,"r")
for line in f:
line2=""
forch in range(len(line)-1,-1,-1):
line2=line2+line[ch]
print line2
[Link]()
Output:
Enter the filename: "[Link]"
.egaugnalgnitpircsdetneiro-tcejbodnaevitcaretni,deterpretni,level-hgih a
sinohtyP
.elbadaerylhgihebotdengisedsinohtyP
.segaugnalrehtonahtsnoitcurtsnoclacitcatnysrewefsahtidna
,noitautcnupesusegaugnalrehtosaerehwyltneuqerfsdrowyekhsilgnEsesutI

b)Writeaprogramtocomputethenumberofcharacters,wordsandlinesi
nafile.
Program:
filename=input("Enter the filename:")
f=open(filename,"r")
l=w=c=0for
line in f:
words=[Link]()
l=l+1
for word in words:
w=w+1
forchinword:
c=c+1
print"[Link]",l
print"[Link]",w
print"[Link]",cf.
close()
Output:
Enter the filename: "[Link]"
[Link] 3
[Link] words [Link]
characters 237

Page10
PYTHONPROGRAMMINGLAB MANUAL

Exercise-8Functions
a)Writeafunctionball_collidethattakestwoballsasparametersandco
[Link]
sentingwhetherornottheballsarecolliding.

Hint:Represent aballonaplane as atuple of (x, y, r), r being the radius


If(distancebetweentwoballscenters)<=(sumoftheirradii)then(they
arecolliding)

Program:
import math
defball_collide(x1,y1,r1,x2,y2,r2):
status=False
d=[Link]((x2-x1)**2-(y2-y1)**2)
r=r1+r2
if(d<r):
status=True
else:
status=False
return status
s=ball_collide(1,2,4,111,102,3)
print"Balls Collisionis",s
s=ball_collide(1,2,2,101,102,3)
print"Balls Collisionis",s

Output:
BallsCollisionisFalse
BallsCollisionisTrue

Page11
PYTHONPROGRAMMINGLAB MANUAL

b)Findmean,median,modeforthegivensetofnumbersinalist.

Program:

def mean(a):
s=sum(a)
m1=float(s)/len(a)
print "Meanis",m1
def median(a):
[Link]()
n=len(a)
if n%2==0:
m2=float((a[n/2]+a[(n-1)/2])/2)
else:
m2=b[(n-1)/2]print
"Median is",m2
def mode(a):
s1=set()
uniq=[ ]
for x ina:
ifx ins1:
[Link](x)
[Link](x)
print "Mode
is",uniqlst=[1,1,2,2,3,
4,5,6] mean(lst)
median(lst)
mode(lst)

Output:
Mean is 3.0
Median is2.0
Mode is [1, 2]

Page12
PYTHONPROGRAMMINGLAB MANUAL

Exercise-9Functions-Continued
a)Writeafunctionnearly_equaltotestwhethertwostringsarenearlye
[Link]
glemutationonb.
Program:
defmutate(word):o
ut_list =[]
letters = 'abcdefghijklmnopqrstuvwxyz'
#insertacharacter
fori in range(len(word) + 1):
for jinrange(26):
out_list.append(word[:i] + letters[j]+ word[i:])
#deletingacharacter
for i in range(len(word)):
out_list.append(word[:i] + word[i+ 1:])
#replaceacharacter for
i in range(len(word)):
for jinrange(26):
out_list.append(word[:i] + letters[j]+ word[i + 1:])
#swappingacharacters
current_word= []
out_word = ''
fori in range(len(word) - 1):
for jinrange(i + 1, len(word)):
#convertingstringintolistcw
ord = list(word)
#Swappingofcharactersinalistcword[i]
,cword [j]= cword[j], cword [i]
#convertinglistintostring
str1="".join(current_word)
out_list.append(str1)
returnout_list

defnearly_equal(word1, word2):
ifabs(len(word1)-len(word2))>1:
returnFalse
ifabs(len(word1)-len(word2))==1:
return word1in mutate(word2)
iflen(word1)<len(word2):
word1,word2=word2,word1
return word1in mutate(word2)
iflen(word1)==len(word2):return
word1in mutate(word2)
str1=input("Enter First Word: ")
str2=input("Enter Second Word:")
res=nearly_equal(str1,str2)
printres

Page13
PYTHONPROGRAMMINGLAB MANUAL

Output-1:
Enter FirstWord:"welcome"
Enter Second Word:"welcoe"
True
Output-2:
Enter FirstWord:"welcome" Enter
Second Word:"welcoome" True
Output-3:
Enter FirstWord:"welcome"
Enter Second Word:"welcometoyou"
False

b)[Link]
m:
defdup(a):
s=set()
d=set()
for i in a:
ifi in s:
[Link](i)
else:
[Link](i)
print "Duplicate elementsare",d
dup([1,1,2,3,4,5,5,4,7,2])

Output:
Duplicate elementsareset([1, 2,4, 5])
c)[Link]
m:
defuni(a):
s=set()
d=set()
u=set()
for i in a:
ifi in s:
[Link](i)
else:
[Link](i)
fori in a:
ifi not in d:
[Link](i)
print "unique elements
are",uuni([1,1,2,3,4,5,5,4,7,2])

Output:
unique elementsare set([3, 7])

Page14
PYTHONPROGRAMMINGLAB MANUAL

Exercise-10-Functions-ProblemSolving

a)Writeafunctioncumulative_producttocomputecumulativeproduct
ofalistofnumbers.
Program:
defcumulative_product(a):
p=1
product=[]
for i in a:
p
*=[Link]
(p)
print
"cumulative_productis",productcumulati
ve_product([1,2,3,4,5])
Output:
cumulative_product is [1, 2,6, 24, 120]

b)[Link]
ction.
defrev_list(a):
b=[]
fori in range(len(a)-1,-1,-1):
[Link](a[i])
print b
rev_list([11,12,13,14,15])
Output:
[15, 14, 13, 12, 11]

c)Writefunctiontocomputegcd,[Link]
ldn’texceedoneline.
defgcd(x,y):
return x ify==0else gcd(y,x%y)
deflcm(x,y):
return(x*y)//gcd(x,y)
print"gcdis",gcd(54,24)
print"lcm is",lcm(54,24)
Output:
gcdis6
lcmis 216
PYTHONPROGRAMMINGLAB MANUAL

Exercise11-Multi-DLists
a)Writeaprogramthatdefinesamatrixandprints

r1=input("Enter AMatrixRows:")
c1=input("Enter A MatrixColumns:")
a=[]
foriinrange(r1):
[Link]([])
foriinrange(r1):for j
in range(c1):
a[i].insert(j,input("Enter value:"))
print"a=",a
r2=input("Enter BMatrixRows:")
c2=input("Enter BMatrix Columns:")
b=[]
foriinrange(r2):
[Link]([])
foriinrange(r2):for j
in range(c2):
b[i].insert(j,input("Enter value:"))
print"b=",b
Output:
Enter A Matrix Rows:3
Enter A Matrix Columns:3
Enter value:1
Enter value:2
Enter value:3
Enter value:4
Enter value:5
Enter value:6
Enter value:7
Enter value:8
Enter value:9
a= [[1, 2,3], [4, 5,6], [7, 8,9]]
Enter BMatrixRows:3
Enter BMatrixColumns:3
Enter value:1
Enter value:2
Enter value:3
Enter value:4
Enter value:5
Enter value:6
Enter value:7
Enter value:8
Enter value:9
b= [[1, 2,3], [4,5,6], [7, 8,9]]

Page16
PYTHONPROGRAMMINGLAB MANUAL

b)Writeaprogramtoperformadditionoftwosquarematrices

r1=input("Enter AMatrixRows:")
c1=input("Enter A MatrixColumns:")
a=[]
foriinrange(r1):
[Link]([])
foriinrange(r1):for j
in range(c1):
a[i].insert(j,input("Enter value:"))
print"a=",a
r2=input("Enter BMatrixRows:")
c2=input("Enter BMatrix Columns:")
b=[]
foriinrange(r2):
[Link]([])
foriinrange(r2):for j
in range(c2):
b[i].insert(j,input("Enter value:"))
print"b=",b
ifr1==r2andc1==c2:
c=[]
fori in range(r1):
[Link]([])
fori in range(r1):for
jinrange(c1):
c[i].insert(j,a[i][j]+b[i][j])
for i in range(r1):
for jinrange(c1):
printc[i][j],"\t",
print ""

else:
print "Addition isNOTPossible"
Output:
Enter A Matrix Rows:3
Enter A Matrix Columns:3
Enter value:1
Enter value:2
Enter value:3
Enter value:4
Enter value:5
Enter value:6
Enter value:7
Entervalue:8
Enter value:9
a= [[1, 2,3], [4, 5,6], [7, 8,9]]

Page17
PYTHONPROGRAMMINGLAB MANUAL

Enter BMatrixRows:3
Enter BMatrixColumns:3
Enter value:4
Enter value:5
Enter value:6
Enter value:7
Enter value:8
Enter value:9
Enter value:1
Enter value:2
Enter value:3
b= [[4, 5,6], [7,8,9], [1, 2,3]]

5 7 9
11 13 15
8 10 12

c)Writeaprogramtoperformmultiplicationoftwosquarematrices
Program:

r1=input("Enter AMatrixRows:")
c1=input("Enter A MatrixColumns:")
a=[]
foriinrange(r1):
[Link]([])
foriinrange(r1):for j
in range(c1):
a[i].insert(j,input("Enter value:"))
print"a=",a
r2=input("Enter BMatrixRows:")
c2=input("Enter BMatrix Columns:")
b=[]
foriinrange(r2):
[Link]([])
foriinrange(r2):for j
in range(c2):
b[i].insert(j,input("Enter value:"))
print"b",b
ifc1==r2:
c=[]
fori in range(r1):
[Link]([])
fori in range(r1):for
jinrange(c2):
x=0

Page18
PYTHONPROGRAMMINGLAB MANUAL

for k in range(c1):
x+=a[i][k]*b[k][j]
c[i].insert(j,x)
for i in range(r1):
for jinrange(c1):
printc[i][j],"\t",
print ""
else:
print "Multiplication isNOTPossible"
Output:
Enter A Matrix Rows:3
Enter A Matrix Columns:3
Enter value:1
Enter value:2
Enter value:3
Enter value:4
Enter value:5
Enter value:6
Enter value:7
Enter value:8
Enter value:9
a= [[1, 2,3], [4, 5,6], [7, 8,9]]
Enter BMatrixRows:3
Enter BMatrixColumns:3
Enter value:4
Enter value:5
Enter value:6
Enter value:1
Entervalue:2
Enter value:3
Enter value:7
Enter value:8
Enter value:9
b[[4, 5,6], [1,2, 3], [7, 8,9]] 27
33 39
63 78 93
99 123147

Page19
PYTHONPROGRAMMINGLAB MANUAL

Exercise-12-Modules
a)Installpackagesrequests,[Link](pip)

 [Link]
download install the packages follow thecommands
 InstallationofrequestsPackage:
 Command: cd C:\Python27\Scripts
 Command: pip installrequests

 InstallationofflaskPackage:
 Command: cd C:\Python27\Scripts
 Command: pip installflask

b)[Link]
.(Wiki)
import requests
r = [Link]('[Link]
printr.status_code
[Link]['content-type']
[Link]

c)WriteasimplescriptthatservesasimpleHTTPResponseandasimpleH
TMLPage
Program:[Link]
from flask importFlask,render_template
app= Flask(__name__)
print(app)
@[Link]("/")
def main():
returnrender_template('[Link]')
if__name__=="__main__":
[Link](host="[Link]" ,port=2500)

Page20
PYTHONPROGRAMMINGLAB MANUAL

Program:[Link]
<!DOCTYPEhtml>
<html>
<body>
<a href="[Link] is a
link</a></body>
</html>

 Run the [Link] python program

 Goto Browser [Link]

 ClickThe Linkin theshown and itwill goto website link

Page21
PYTHONPROGRAMMINGLAB MANUAL

Exercise-13OOP
a)DescribeaboutClassvariableusingRobotClassProg
ram:
class Robot:
what="Machine"#class Variable
name="Chitti"
version=1.0
speed="1THz"
memory="1ZB"
defupdate(cls):
[Link]=2.0
[Link]="2THz"
[Link]="2ZB"
r=Robot()
print"Hai i am a",[Link]
print"My Name is",[Link]
print"Version",[Link]
print"Speed",[Link]"
Memory",[Link]
e()
print""
print"Hai i am a",[Link]
print"My Name is",[Link]
print"Version",[Link]
print"Speed",[Link]"
Memory",[Link]

Output:
Haiiam a Machine
MyName isChitti
Version1.0
Speed 1THz
Memory 1ZB

Haiiam a Machine
MyName isChitti
Version2.0
Speed 2THz
Memory 2ZB

Page22
PYTHONPROGRAMMINGLAB MANUAL

b)DescribeaboutInstancevariableusingATMMachineClassProg
ram:
classATM:
def __init__(self):
[Link]=0#instance Variable
print "New AccountCreated"
defdeposit(self):
amount=input("Enter the amount to deposit: ")
[Link]=[Link]+amount
print "New Balance
is",[Link] withdraw(self):
amount=input("Enter the amount to withdraw: ")
[Link]<amount:
print"Insufficient Balance"
else:
[Link]=[Link]-amount
print"New Balance is",[Link]
def enquiry(self):
print "The Balance is",[Link]
a=ATM()
[Link]()
[Link]()
[Link]()
[Link]()
Program:
New AccountCreated
Enter the amount todeposit:1200
New Balance is1200
Enter the amount towithdraw:950
New Balance is250
Enter the amount towithdraw:120
New Balance is130
The Balance is130

Page23
PYTHONPROGRAMMINGLAB MANUAL

Exercise-14GUI,Graphics
a)WriteaGUIforanExpressionCalculatorusingtkProgr
am:

fromTkinter import*
from math import *

root=Tk()
[Link]("Calculator")
[Link]("210x200")

e=Entry(root,bd=8,width=30)
[Link](row=0,column=1,columnspan=5)

defsetText(txt):
l=len([Link]())
[Link](l,txt)

def clear1():
txt=[Link]()
[Link](0,END)
[Link](0,txt[:-1])

def clear():
[Link](0,END)

defsqroot():
txt=sqrt(float([Link]()))
[Link](0,END)
[Link](0,txt)

defnegation():
txt=[Link]()
if txt[0]=="-":
[Link](0,END)
[Link](0,txt[1:])
eliftxt[0]=="+":
[Link](0,END)
[Link](0,"-"+txt[1:])
else:[Link](0,"-
")

Page24
PYTHONPROGRAMMINGLAB MANUAL

def equals():
try:
s=[Link]()
foriinrange(0,len(s)):
if s[i]=="+" ors[i]=="-" or s[i]=="*" ors[i]=="/" or s[i]=="%":
expr=str(float(s[:i]))+s[i:]
break
elif s[i]==".":
expr=s
break
[Link](0,END)
[Link](0,eval(expr))
exceptException:
[Link](0,END)
[Link](0,"INVALID EXPRESSION")

back1=Button(root,text="<--",command=lambda:clear1(),width=10)
[Link](row=1,column=1,columnspan=2)
sqr=Button(root,text=u'\u221A',command=lambda:sqroot(),width=4)
[Link](row=1,column=5)
can=Button(root,text="C",command=lambda:clear(),width=4)
[Link](row=1,column=3)
neg=Button(root,text="+/-",command=lambda:negation(),width=4)
[Link](row=1,column=4)

nine=Button(root,text="9",command=lambda:setText("9"),width=4)
[Link](row=2,column=1)
eight=Button(root,text="8",command=lambda:setText("8"),width=4)
[Link](row=2,column=2)
seven=Button(root,text="7",command=lambda:setText("7"),width=4)
[Link](row=2,column=3)

six=Button(root,text="6",command=lambda:setText("6"),width=4)
[Link](row=3,column=1)
five=Button(root,text="5",command=lambda:setText("5"),width=4)
[Link](row=3,column=2)
four=Button(root,text="4",command=lambda:setText("4"),width=4)
[Link](row=3,column=3)

three=Button(root,text="3",command=lambda:setText("3"),width=4)
[Link](row=4,column=1)
two=Button(root,text="2",command=lambda:setText("2"),width=4)
[Link](row=4,column=2)
one=Button(root,text="1",command=lambda:setText("1"),width=4)
[Link](row=4,column=3)

Page25
PYTHONPROGRAMMINGLAB MANUAL

zero=Button(root,text="0",command=lambda:setText("0"),width=10)
[Link](row=5,column=1,columnspan=2)

dot=Button(root,text=".",command=lambda:setText("."),width=4)
[Link](row=5,column=3)

div=Button(root,text="/",command=lambda:setText("/"),width=4)
[Link](row=2,column=4)

mul=Button(root,text="*",command=lambda:setText("*"),width=4)
[Link](row=3,column=4)

minus=Button(root,text="-",command=lambda:setText("-"),width=4)
[Link](row=4,column=4)

plus=Button(root,text="+",command=lambda:setText("+"),width=4)
[Link](row=5,column=4)

mod=Button(root,text="%",command=lambda:setText("%"),width=4)
[Link](row=2,column=5)

byx=Button(root,text="1/x",command=lambda:setText("%"),width=4)
[Link](row=3,column=5)

equal=Button(root,text="=",command=lambda:equals(),width=4,
height=3)
[Link](row=4,column=5,rowspan=2)

[Link]()

Page26
PYTHONPROGRAMMINGLAB MANUAL

b)Writeaprogramtoimplement

import turtle
c=["red","green","blue"]
i=0
[Link](5)
for angle inrange(0,360,30):
if i>2:
i=0
[Link](c[i])
[Link](angle)
[Link](50)
i=i+1

[Link]

import turtle
[Link](2)
for iinrange(36):
for j in range(4):
[Link](70)
[Link](90)
[Link](10)

Page27
PYTHONPROGRAMMINGLAB MANUAL

Exercise-15-Testing
a)Writeatest-
casetochecktheeven_numberswhichreturnTrueonpassingalistofalle
vennumbers
Program:
num= input('Enter any number: ')
if num % 2 ==0:
print(num, "is EVEN")
else:
print(num, "is ODD")
Testcase-1: Positive Even Number

Testcase-2: Positive Odd Number

Testcase-3: Negative Even Number

Testcase-4: Negative OddNumber

Testcase-5:Zero

b)Writeatest-
casetocheckthefunctionreverse_stringwhichreturnsthereversed
string.
Program:
defreverse_string(string):
str2=""
fori in range(len(string)-1,-1,-1):
str2=str2+string[i]
printstr2
a = input("Enter thestring to be reversed: ")
reverse_string(a)
TestCase-1:

TestCase-2:
Page28
PYTHONPROGRAMMINGLAB MANUAL

Exercise-16-
Advanceda)Buildanyoneclassicaldatastructure

import sys
a=[]
while True:
print "\[Link] [Link] [Link] [Link]"
ch=input("Enter Your Choice: ")
ifch==1:
ele=input("Enter element:")
[Link](ele)
print "Inserted"
elifch==2:
iflen(a)==0:
print"\tSTACK IS EMPTY"
else:
print"Deleted element is",a[len(a)-1]
[Link](a[len(a)-1])
elifch==3:
iflen(a)==0:
print"\tSTACK IS EMPTY"
else:
print"\tTheElements in Stack is",
for iin a:
printi,
elifch==4:
[Link]()
else:
print "\tINVALID CHOICE"

Output:
[Link] [Link] [Link]
Enter Your Choice:1
Enter element: 15
Inserted
[Link] [Link] [Link]
Enter Your Choice:1
Enter element: 16
Inserted
[Link] [Link] [Link]
Enter Your Choice:1
Enter element: 17
Inserted
[Link] [Link] [Link]
Enter Your Choice:3
The Elements inStack is 15 1617

Page29
PYTHONPROGRAMMINGLAB MANUAL

[Link] [Link] [Link]


Enter Your Choice:2
Deleted element is 17
[Link] [Link] [Link]
Enter Your Choice: 3
The Elements inStack is 15 16
[Link] [Link] [Link]
Enter Your Choice:3
The Elements inStack is 15 16
[Link] [Link] [Link]
Enter Your Choice:4
b)[Link]
rtitertools
def knapsack(n,wt,profit,W):
d=dict(zip(wt,profit))
d2=dict()
fori in range(0,n+1):
for jin [Link](wt,i):
kwt=0
kprof=0
for key inj:
kprof =kprof + d[key]
kwt = kwt+ key
ifkwt<=W:
d2[j]=kprof
forkey,value in [Link]():
ifvalue==max([Link]()):
print"MaxProfit is",key,value
n=input("enter [Link] items:")
wt=[]
profit=[]
foriinrange(n): [Link](input("Enter
Weight: "))
[Link](input("Enter Profit:"))
W=input("Enter Maximum Weight: ")
knapsack(n,wt,profit,W)

Output:
enter no. of items:3
Enter Weight: 10
Enter Profit:60Enter
Weight: 20 Enter
Profit:100
EnterWeight: 30
Enter Profit:120
Enter MaximumWeight:50
Max Profit is (20, 30) 220

Page30

You might also like