25150L17 - Python Lab Manual
25150L17 - Python Lab Manual
.
6.1 GCDofgiven numbers using Euclid's Algorithm.
6.2 Squareroot ofagiven numberusing newtons method.
6.3 Factorialof anumber using functions
6.4 largestnumberinalist
6.5 Areaof shapes
7 ImplementingprogramsusingStrings.
7.1 Reverseof astring
7.2 Palindromeof a string
7.3 Charactercountof a string
7.4 Replaceofastring
8 ImplementingprogramsusingwrittenmodulesandPython Standard
Libraries.
8.1 Convertlist into aSeries using pandas
8.2 Findingtheelementsofagivenarrayiszerousingnumpy
8.3 Generateasimplegraphusing matplotlib
8.4 Solvetrigonometricproblemsusing scipy
9 Implementingreal-time/technicalapplicationsusingFilehandling.
9.1 Copy text from onefiletoanother
9.2 CommandLineArguments(WordCount)
9.3 Findthelongest word(Filehandling)
10 Implementingreal-time/technicalapplicationsusingException
handling.
10.1 Dividebyzero error–Exception Handing
10.2 Voter’sage validity
10.3 Studentmarkrange validation
11 ExploringPygame tool.
12 Developing a gameactivity using Pygame
12.1 SimulateBouncing BallUsing Pygame
12.2 SimulateCarrace UsingPygame
.
Ex : 1.1
ElectricityBilling
Date:
Aim:
Towriteapython program toprint electricity bill.
Algorithm:
.
Flowchart:
.
Program:
cr=int(input("Enter current month reading"))
pr=int(input("Enterpreviousmonthreading"))
consumed=cr - pr
if(consumed>=1andconsumed<=100):
amount=consumed * 2
print("your bill is Rs.", amount)
elif(consumed>100andconsumed<=200):
amount=consumed * 3
print("yourbillisRs.",amount)
elif(consumed>200and consumed<=500):
amount=consumed * 4
print("yourbillisRs.",amount)
elif(consumed>500):
amount=consumed * 5
print("yourbillisRs.",amount)
else:
print("Invalidreading")
.
Output:
Enter current month reading 500
Enterpreviousmonthreading200 your
bill is Rs. 1200
Result:
.
Thusthepythonprogram forgeneratingelectricity billis executedandtheresults
areverified
Ex : 1.2
Pythonprogram forsinseries
Date:
Aim:
Towriteapythonprogramforsinseries.
Algorithm:
Step 1 : Start
Step 2 : Readthevaluesofxandn
Step 3 : Initialize sine=0
Step 4 : Defineasinefunctionusing forloop, firstconvertdegreesto radians.
Step 5 : Computeusingsineformulaexpansionandaddeachtermtothesumvariable. Step 6
: Print the final sum of the expansion.
Step 7 : Stop.
.
FlowChart:
.
Program:
importmath
x=int(input("Enterthevalueofxindegrees:"))
n=int(input("Enter the number of terms:"))sine
=0
foriinrange(n):
sign=(-1)**i
pi=22/7
y=x*(pi/180)
sine=sine+((y**(2.0*i+1))/math.factorial(2*i+1))*sign print(sine)
.
Result:
Aim:
Towriteapythonprogram to calculatetheweightof amotor bike.
Algorithm:
Step1: Starttheprogram
Step2:Read thevalue ofamass
Step3:Calculatetheweightofamotorbikebymultiplyingmasswith9.8andstoreitinweight Step 4:
Print the weight
Step 5: Stop
Flow chart:
Start
EnterthevalueM
(mass)OfMotorbike
Initializeg(gravity)=9.8
Compute W=m*g
PrinttheWeight
Stop
.
Program:
mass=float(input("EntertheMassof theMotorBike: "))
Weight =mass*9.8
print(“Theweightof aMotor Bikefor agivenmassis ”,Weight)
Output:
EntertheMass ofthe MotorBike: 100
Theweight of aMotor Bike for agiven mass is980.0000000000001
Result: .
Thusthe pythonprogramtocalculate theweight of amotor bikeis executed and
theresultsareverified.
Ex : 1.4
WeightofaSteel Bar
Date:
Aim:
Towriteapython program to calculatetheweight of asteel bar.
Algorithm:
Step1: Starttheprogram
Step2:Read thevalueof adiameterand length
Step3:Calculatetheweightofasteelbarbyusingtheformulaof ((diameter*diameter)/162.28)*length
and store it in weight.
Step4:Printweight
Step 5: Stop
Flow chart:
Start
EnterthevalueM
(mass)OfMotorbike
Initializeg(gravity)=9.8
Compute W=m*g
PrinttheWeight
Stop
.
Program:
diameter=float(input("EntertheDiameteroftheRoundedSteelBar:"))
length = float(input("Enter the Length of the Rounded Steel Bar:"))
Weight=((diameter*diameter)/162.28)*length
print(“Weight of a Steel Bar”,Weight)
Output:
EntertheDiameteroftheRoundedSteelBar:2 Enter
the Length of the Rounded Steel Bar:15 Weight
of aSteel Bar is 0.3697313285679073
Result:
Thusthepythonprogramtocalculatethe.weightofasteelbarisexecutedand the
resultsareverified.
Ex : 1.5
ElectricalCurrentinThreePhaseACCircuit
Date:
Aim:
TowriteapythonprogramtocalculatetheelectricalcurrentinThreePhaseACCircuit.
Algorithm:
Step1: Starttheprogram.
Step 2: Read all the values of resistance, frequency and voltage.
Step3:CalculatetheelectricalcurrentinthreephaseACCircuit. Step
4: Print the result.
Step 5: Stop
Flow Chart:
Start
Initalizethevaluesfor R,X_L,V_L,f
Compute
V_Ph=V_L/1.732 # in V Z_Ph=sqrt((R**2)+(X_L**2))#inohm I_Ph=V_Ph/Z_Ph# in A
I_L=I_Ph#inA
PrintthekW
Stop
.
Program:
importmath
R = 20 # in ohm
X_L=15#inohm
V_L = 400 # in V
f = 50 # in Hz
#calculations
V_Ph=V_L/1.732#inV
Z_Ph=sqrt((R**2)+(X_L**2))#inohm
I_Ph=V_Ph/Z_Ph# in A
I_L=I_Ph#inA
print("TheElectricalCurrentinThreePhaseACCircuit",round(I_L,6))
Output:
TheElectricalCurrentinThreePhase ACCircuit9.237604
Result:
ThusthepythonprogramtocalculatetheelectricalcurrentinThreePhase AC
Circuitisexecutedandtheresultsareverified.
Ex : 2.1
Exchangingthevaluesoftwovariablesin python
Date:
Aim:
Algorithm:
Step 1 : Start
Step2:Defineafunctionnamedformat()
Step 2 : Read the input values X and Y
Step 3 : Perform the followingsteps
Step 3.1 : temp = x
Step 3.2: x = y
Step3.3:y=temp
Step4:Printtheswappedvalueasresult Step
5 : End
Program:
UsingTemporaryvariable
#Totakeinputsfrom theuser
x=input('Entervalueofx:')
y=input('Entervalue of y: ')
#createatemporaryvariableandswapthevalues temp
=x
x =y
y =temp
print('Thevalueofxafterswapping:',x)
print('Thevalueofyafterswapping: ',y)
output:
Entervalueofx: 10
20
Entervalueofy:
Thevalue ofxafter swapping: 20 .
Thevalue ofyafter swapping: 10
FewOtherMethodstoSwapvariablesWit
hout Using Temporary variable
Program:
x =5
y =10
x, y = y, x
print("x=",x)
print("y=",y)
output:
x =10
y =5
UsingAdditionandSubtractionProgram:
x =15
y =10
x=x+y y
=x-yx
=x – y
print('Thevalueofxafterswapping:'x)
print('Thevalueofy afterswapping:'y)
output:
x =10
y =15
UsingMultiplicationandDivisionProgra
m:
x =25
y =10
x=x*y y
=x/yx
=x/y
print('Thevalueofxafterswapping:'x)
print('Thevalueofy afterswapping:'y)
output: >>>x10.0 .
>>>y25.0
SwappingusingXOR:
x =35
y =10
x=x^y
y=x^y x
=x ^ y
output:
>>>x
10
>>>y
35
.
Result
Aim:
Algorithm:
Step 1 : Start
Step 2 : Declarealist
Step 3 : Read number of input value.
Step 4 : Storethevalueofinputinlist.
Step 5 : Print the original list.
Step 6 : Userangefunctionwithforlooptocirculatethevalues Step
7: Print the result
Program:
A=list(input("EnterthelistValues:"))
print(A)
foriinrange(1,len(A),1): print(A[i:]+A[:i])
Result
Thus,thePythonprogramtoCirculateth.evaluesofnvariableswasexecuted
successfullyand theoutput is verified.
Ex : 2.3
Distancebetweentwopoints
Date:
Aim:
Writeapythonprogram tocalculate distancebetweentwo pointstaking inputfrom theuser.
Algorithm:
Step 1 : Start
Step 2 : Definea function math.sqrt()
Step 3 : ReadthevalueofcoordinatesoftwopointsP1andP2 Step
4: Perform the following step
Step 5 : dist=math.sqrt(((x2-x1)**2)+((y2-y1)**2))
Step 6 : Print the distance between two points
Step 7 : End
Program:
importmath
print("EntercoordinatesforPoint1:") x1 =
int(input("x1 = "))
y1 =int(input("y1 ="))
print("Entercoordinatesforpoint2:") x2 =
int(input("x2 = "))
y2 =int(input("y2 ="))
dist = math.sqrt( ((x2-x1)**2) + ((y2-y1)**2) )
print("Distancebetweengivenpointsis",round(dist,2))
Output:
EntercoordinatesforPoint1: x1
=2
y1 =3
Entercoordinatesforpoint2: x2
=3
y2 =4
Distancebetweengivenpointsis 1.41
.
Result
Thus,thePythonprogramtocalculatedistancebetweentwopointswasexecutedsuccessfully and
the output is verified.
Ex : 3.1
NumberSeries-Fibonacci Series
Date:
Aim:
ToWriteapythonprogram toprint Fibonacciseries takinginput fromtheuser
Algorithm:
Step1 :Start
Step2:Readtheinputvaluesusinginput() Step
3 :Assign f1= -1 and f2=1.
Step 4 :Perform the term = f1+f2
Step 5 :Print the value as result
Step6:Performthefollowingswap
Step 7 :step f1 = f2
Step8:f2=term Step 9
:End
Program:
# Fibonacci series
print("Fibonacciseries")
Num_of_terms=int(input("Enternumberofterms:")) f1 =
-1
f2 =1
foriinrange(0,Num_of_terms,1): term
= f1+f2
print(term,end="")
f1 = f2
f2 =term
Output:
Fibonacciseries:
Enternumberofterms:5 0
1123
Result .
Thus,thePythonprogram toprintFibonacciseries wasexecutedsuccessfullyand the
output is verified.
Result .
Thus,thePythonprogram toprintFibonacciseries wasexecutedsuccessfullyand the
output is verified.
Ex : 3.2
NumberSeries -Odd Numbers
Date:
Aim:
Towriteapython program to print oddnumbers bytaking input from theuser
Algorithm:
Step 1 : start
Step 2 : Declare the list of numbers using list.
Step 3 : Useforlooptoiteratethenumbersinlist.
Step 4 : Check for condition
Step 5 : Num % 2==0
Step 6 : Printtheresult.
Step 7 : End
Program:
# list of numbers
list1 =[10,21, 4, 45, 66, 93]
#iteratingeachnumberinlist for
num in list1:
#checkingcondition if
num % 2 != 0:
print(num,end="")
Output:
Enter number of terms:
5NumberPatterns-OddNumbers:
13579
Result .
Thus,thePythonprogramtoprintoddnumberswasexecutedsuccessfullyandthe output
is verified.
Ex : 3.3
NumberPattern
Date:
Aim:
To writeapython program to print numbers patterns.
Algorithn:
Step1: Starttheprogram.
Step2:Declarethevalue forrows.
Step3:Let iand jbeaninteger number.
Step4:Repeat step5 to8until allvalue parsed
Step5:Setiinouterloopusingrangefunction,i=rows+1and rowswillbeinitializedtoi Step 6: Set j
in inner loop using range function and i integer will be initialized to j
Step7:Print iuntil thecondition becomesfalse ininner loop.
Step8:Printnewlineuntiltheconditionbecomesfalseinouterloop. Step 9:
Stop the program.
Program:
rows=int(input('Enterthenumberofrows')) for
i in range(rows+1):
for j in range(i):
print(i,end='')
print('')
Output:
Enterthenumberofrows 6
1
22
333
4444
55555
666666
Result:
Thusthepythonprogram toprintnumberspatterns isexecutedandverified.
Ex : 3.4
Pyramid Pattern
Date:
Aim:
Towriteapython program toprint pyramid patterns
Algorithm:
Program:
n=int(input("Enterthenumberofrows:")) m =
(2 * n) - 2
fori in range(0, n):
forjinrange(0,m):
print(end="")
m=m-1#decrementingmaftereachloop for j
in range(0, i + 1):
#printingfullTrianglepyramidusingstars
print("* ", end='')
print("")
Output:
Enter thenumberof rows: 5
*
**
***
****
*****
Result
Thus,thePythonprogramtoprintPyramidPatternwasexecutedsuccessfullyandtheoutput is
verified.
.
Ex : 4.1
Implementingreal-time/technicalapplicationsusingLists Basic
Date: operations of List
Aim:
Step 1 : Start
Step 2 : Declarealist
Step 3 : Readtheinputvalue.
Step 4 : Storethe value ofinput inlist.
Step 5 : Processthelistfunctionspresentinlibraryfunction.
Step 6 : Print the result
Step 7 : End
Program:
#creatinga list
Library=['OS','OOAD','MPMC']
print("Booksinlibraryare:")
print(Library)
OUTPUT:
Booksinlibrary are:
['OS','OOAD','MPMC']
#AccessingelementsfromtheList
Library=['OS','OOAD','MPMC']
print("Accessingaelementfromthe
list") print(Library[0])
print(Library[2])
OUTPUT:
Accessingaelementfromthe list
OS
MPMC
#CreatingaMulti-DimensionalList .
Library=[['OS','OOAD','MPMC'], ['TOC','PYTHON','NETWORKS']]
print("AccessingaelementfromaMulti-Dimensionallist")
print(Library[0][1])
print(Library[1][0])
OUTPUT:
AccessingaelementfromaMulti-DimensionallistOOAD
TOC
#Negativeindexing
Library=['OS','OOAD','MPMC']
print("Negativeaccessingaelementfromthelist")
print(Library[-1])
print(Library[-2])
OUTPUT:
Negativeaccessingaelementfromthe list
MPMC
OOAD
#Slicing
Library=['OS','OOAD','MPMC','TOC','NW']
print(Library[1][:-3])
print(Library[1][:4])
print(Library[2][2:4])
print(Library[3][0:4])
print(Library[4][:])
OUTPUT:
OOOADMCTOCNW
#append()
Library=['OS','OOAD','MPMC']
Library.append(“DS”)Li
brary.append(“OOPS”)Li
brary.append(“NWs”)pr
int(Library)
OUTPUT:
['OS','OOAD', 'MPMC', 'DS', 'OOPS', 'NWs']
#extend()
Library=['OS','OOAD','MPMC']
Library.extend(["TOC","DWDM"])
print(Library)
.
OUTPUT:
['OS','OOAD', 'MPMC','TOC', 'DWDM']
#insert()
Library=['OS','OOAD','MPMC']
Library.insert(0,”DS”)
print(Library)
OUTPUT:
['DS','OS','OOAD','MPMC']
#delmethod
Library=['OS','OOAD','MPMC']
delLibrary[:2]
print(Library)
OUTPUT:
['MPMC']
#remove()
Library=['OS','OOAD','MPMC','OOAD']
Library.remove('OOAD')
print(Library)
OUTPUT:
['OS','MPMC', 'OOAD']
#reverse()
Library=['OS','OOAD','MPMC']
Library.reverse()
print(Library)
OUTPUT:
['MPMC','OOAD','OS']
#sort()
Library=['OS','OOAD','MPMC']
Library.sort()
print(Library)
OUTPUT:
['MPMC','OOAD','OS']
#+concatenationoperator
Library=['OS','OOAD','MPMC']
Books=['DS','TOC','DMDW']
print(Library+Books) .
OUTPUT:
['OS','OOAD', 'MPMC','DS', 'TOC', 'DMDW']
# *replication operator
Library=['OS','OOAD','MPMC','TOC','NW']
print('OS' in Library)
print('DWDM'inLibrary)
print('OS' not in Library)
OUTPUT:
True
False
False
#count()
Library=['OS','OOAD','MPMC','TOC','NW']
x=Library.count("TOC")
print(x)
OUTPUT:
1
Result
Thus,thePythonusinglistfunctionspresentinlistlibrary wasexecutedsuccessfullyand the
output is verified.
.
Ex : 4.2
Libraryfunctionalityusinglist.
Date:
Aim:
Towriteapythonprogram toimplement thelibrary functionalityusing list.
Algorithm:
Step 1 : Start the program
Step 2 : Initializethebooklist
Step 3 : Getoption fromtheuser foraccessingthe library function
Add thebook to list
Issueabook
Returnthe book
Viewthelist of book
Step 4 : ifchoiceis1 thenget bookname andadd tobooklist
Step 5 : ifchoiceis2thenissuethebookandremovefrombooklist Step 6
: if choice is 3 then return the book and add the book to list
Step 7 : if choice is 4 then the display the book list
Step 8 : otherwiseexitfrommenu
Step 9 : Stop the program.
Program:
bk_list=["OS","MPMC","DS"]
print("Welcometolibrary”")
while(1):
ch=int(input("\n1.addthebooktolist\n2.issueabook\n3.returnthebook\n4.viewthe book list \n 5.
Exit \n"))
if(ch==1):
bk=input("enterthebookname")
bk_list.append(bk)
print(bk_list)
elif(ch==2):
ibk=input("Enterthebooktoissue")
bk_list.remove(ibk)
print(bk_list)
elif(ch==3):
rbk=input("enterthebooktoreturn")
bk_list.append(rbk)
print(bk_list)
elif(ch==4):
print(bk_list)
else:
break .
Output:
Welcometolibrary”
1. addthebooktolist
2. issueabook
3. returnthebook
4. viewthebooklist
5. Exit
1
enter the book name NW
['OS','MPMC','DS','NW']
1. addthebooktolist
2. issueabook
3. returnthebook
4. viewthebooklist
5. Exit
2
Enter the book to issue
NW['OS','MPMC','DS']
1. addthebooktolist
2. issueabook
3. returnthebook
4. viewthebooklist
5. Exit
3
enter the book to return
NW['OS','MPMC','DS','N
W']
1. addthebooktolist
2. issueabook
3. returnthebook
4. viewthebooklist
5. Exit
4
['OS', 'MPMC', 'DS', 'NW']
Result:
Thusthepythonprogramtoimplementthelibraryfunctionalityusinglistisexecuted andthe
.
resultsareverified
Ex : 4.3
Date: Componentsofcarusinglist
Aim:
Towriteapython programto implement theoperation oflist forcomponents of car.
Algorithm:
Program:
cc=['Engine','Frontxle','Battery','transmision']
com=input('Enter the car components:')
cc.append(com)
print("Components of car :",cc)
print("length of the list:",len(cc))
print("maximumofthelist:",max(cc))
print("minimum of the list:",min(cc))
print("indexing(Value at the index 3):",cc[3])
print("Return'True'ifBatteryinpresentinthelist")
print("Battery" in cc)
print("multiplicationoflistelement:",cc*2)
.
Output:
Enterthecar components:Glass
Componentsofcar:['Engine','Frontxle','Battery','transmision','Glass'] length of
the list: 5
maximum of the list: transmisionminimum
of the list: Battery
indexing(Valueattheindex3):transmision
Return'True'ifBatteryinpresentinthelist
True
multiplicationoflistelement:['Engine','Frontxle','Battery','transmision','Glass', 'Engine',
'Front xle', 'Battery', 'transmision', 'Glass']
Result
variousoperationandresultisverified. .
Thusthepythonprogramto create alistforcomponents ofcar andperformed the
variousoperationandresultisverified. .
Ex : 4.4
Materialrequiredforconstructionofabuildingusinglist.
Date:
Aim:
Towriteapythonprogramtocreatealistformaterialsrequirementofconstructionand perform the
operation on the list.
Algorithm:
Step 1 : Startthe program.
Step 2 : Createalistofconstructionmaterial.
Step 3 : Sort the list using sort function.
Step 4 : Print cc.
Step 5 : Reversethelistusingreversefunction.
Step 6 : Print cc.
Step 7 : Insertyvalue byusingindex position.
Step 8 : Slicethevaluesusingdelfunctionwithstartvalueandendupvalue. Step 9
: Print the cc
Step 10 : Printthepositionofthevalue byusing index function.
Step 11 : Printthevaluesinthelistoftheletter‘n’byusingforloopandmembership operator.
Step 12 : Stop theprogram.
Program:
cc=['Bricks','Cement','paint','wood']
cc.sort()
print("sorted List")
print(cc)
print("ReverseList")
cc.reverse()
print(cc)
print("Insertavalue'glass'tothelist")
cc.insert(0, 'Glass')
print(cc)
print("DeleteList")
del cc[:2]
print(cc)
print("Findtheindexof Cement")
.
print(cc.index('Cement'))
print("NewList")
new=[]
fori in cc:
if "n" in i:
new.append(i)
print(new)
Output:
sortedList
['Bricks','Cement','paint','wood']
Reverse List
['wood','paint','Cement','Bricks']
Insertavalue'glass'to thelist
['Glass','wood', 'paint','Cement', 'Bricks']
DeleteList
['paint','Cement','Bricks']
Find the index of Cement
1
NewList
['paint','Cement']
Result:
Thusthe pythonprogramtocreate alist forconstruction ofabuildingusing listisexecuted
andverified. .
Ex : 4.5
Libraryfunctionsusingtuples
Date:
Aim:
Towriteapythonprogram toimplement thelibrary functionalityusing tuples.
Algorithm
Step 1 : Startthe program
Step 2 : Createatuplenamedasbook.
Step 3 : Adda“NW”toabooktuplebyusing+operator. Step
4: Print book.
Step 5 : Slicingoperationsisappliedtobooktupleoftherange1:2andprintbook. Step
6: Print maximum value in the tuple.
Step 7 : Printmaximum valuein thetuple.
Step 8 : Convertthetupletoalistbyusinglistfunction. Step
9: Delete the tuple.
Step 10 : Stop theprogram.
Program:
book=("OS","MPMC","DS")
book=book+("NW",)
print(book)
print(book[1:2])
print(max(book))
print(min(book))
book1=("OOAD","C++","C")
print(book1)
new=list(book)
print(new)
del(book1)
print(book1)
.
OUTPUT:
('OS','MPMC','DS','NW')
('MPMC',)
OS
DS
('OOAD','C++','C')
['OS', 'MPMC', 'DS', 'NW']
Traceback (mostrecentcalllast):
File"C:/PortablePython3.2.5.1/3.py",line12,in<module>print(book1)
NameError:name'book1' isnot defined
Result:
Thusthepythonprogramtoimplementthelibraryfunctionalityusingtupleis
executedandtheresultsareverified .
Ex : 4.6
Componentsofa carusing tuples.
Date:
Aim:
Towriteapython programto implement thecomponentsof acar using tuples.
Algorithm:
Step 1 : Startthe program
Step 2 : Createatuplenamedascc
Step 3 : Addingavaluetoatupleisbyconvertingtupletoalistandthenassign“Gear”value to y[1]
and convert it to a tuple.
Step 4 : Step3isimplementedforremovingavaluein tuple.
Step 5 : Typefunctionisusedtocheckwhetheritislistortuples. Step
6: Stop the program.
Program:
cc=('Engine','Frontaxle','Battery','transmision')
y=list(cc)#addingavaluetoatuplemeanswehavetoconverttoalisty[1]="Gear"cc=tuple(
y)
print(cc)
y=list(cc)#removingavaluefromtuple.y.remove("Gear")
cc=tuple(y)
print(cc)
new=("Handle",)
print(type(new))
Output:
('Engine','Gear','Battery','transmision')
('Engine', 'Battery', 'transmision')
<class'tuple'>
Result:
Thusthepython programtoimplementcomponents ofacarusingtuples is
executedandverified. .
Ex : 4.7
Constructionofamaterials
Date:
Aim:
Towriteapython program to implement theconstruction ofamaterials using tuples.
Algorithm:
Program:
cm=('sand','cement','bricks','water')
a,b,c,d = cm
#tupleunpacking
print("\nValuesafterunpacking:")
print(a)
print(b)
print(c)
print(d)
print(cm.count('sand'))
print(cm.index('sand'))
new=tuple("sand")
print(new)
print(sorted(cm))
print(type(sorted(cm)))
.
Output :
Valuesafterunpacking:
sand
cement
bricks
water1
0
('s','a','n','d')
['bricks','cement','sand','water']
<class'list'>
Result:
Thusthepythonprogramtocreate atupleformaterialsofconstruction and
performedthevariousoperationsandresultis verified.
.
Ex : 5.1 Implementingreal-time/technicalapplicationsusingSets,
Date: Dictionaries.
Languagesusingdictionaries
Aim:
Towriteapythonprogram to implementthelanguages using dictionaries.
Algorithm:
Step1: Starttheprogram
Step 2 : Createaemptydictionaryusing{}
Step 3 : dict()is usedtocreate adictionary.
Step 4 : To add a value, update() is used in key value pair.Step
5: Calculatethetotalvaluesinthedictionaryusinglen().
Step 6 : Removetheparticularkeyinthedictionarybyusingpop() Step
7: Print the keys in the dictionary by using key()
Step 8 : Print the values in the dictionary by using values()
Step 9 : Printthekeyvaluepairinthedictionaryusingitems() Step
10 : Clear the the key value pair by using clear()
Step 11 : Deletethe dictionarybyusingdel dictionary
Program:
Language={}
print("EmptyDictionary :",Language)
Language=dict({1: "english", "two": "tamil", 3: "malayalam"})
print(" Using dict() the languages are :",Language)
New_Language={4:"hindi",5:"hindi"}#duplicatevaluescancreate
Language.update(New_Language)
print(" the updated languages are :",Language)
print("thelengthofthelanguages:",len(Language))
Language.pop(5)
print("key5hasbeenpoppedwithvalue:",Language) print("
the keys are :",Language.keys())
print("thevaluesare:",Language.values())
print("theitemsinlanguagesare:",Language.items()) Language.clear()
print("Theitemsareclearedindictionary",Language) del
Language
print(Language) .
OUTPUT:
EmptyDictionary: {}
theupdatedlanguagesare:{1:'english',3:'malayalam',4:'hindi','two':'tamil',5:'hindi'} the
theitemsinlanguagesare:dict_items([(1,'english'),(3,'malayalam'),(4,'hindi'),('two', 'tamil')])
Theitemsareclearedindictionary{}
File"C:/
PortablePython3.2.5.1/3.py",line17,in<module>print(Language)
NameError:name'Language'isnotdefined
Result:
Thusthepythonprogramtoimplementlanguagesusingdictionariesis executed
andverified.
.
Ex : 5.2
ComponentsofAutomobileusingdictionaries
Date:
Aim:
Towriteapython programto implement automobileusing dictionaries.
Algorithm:
Step1: Starttheprogram
Step2:Createaemptydictionaryusing{}
Step3:dict() isusedtocreateadictionary.
Step4:Get thevalue inthe dictionary using get()
Step5:adding[key]withvaluetoadictionaryusingindexingoperation. Step 6:
Remove a key value pair in dictionary using popitem().
Step7:Tocheckwhetherkeyisavailableindictionarybyusingmembershipoperatorin. Step 8:
Stop the program.
Program:
auto_mobile={}
print(" Empty dictionary ",auto_mobile)
auto_mobile=dict({1:"Engine",2:"Clutch",3:"Gearbox"})
print(" Automobile parts :",auto_mobile)
print("Thevaluefor2is",auto_mobile.get(2))
auto_mobile['four']="chassis"
print("Updatedauto_mobile",auto_mobile)print(auto_mobile.popitem())
print(" The current auto_mobile parts is :",auto_mobile)
print("Is2availableinautomobileparts")
print(2 in auto_mobile)
OUTPUT:
Emptydictionary{}
Automobileparts:{1:'Engine',2:'Clutch',3:'Gearbox'}The value
for 2 is Clutch
Updatedauto_mobile{1:'Engine',2:'Clutch',3:'Gearbox','four':'chassis'}(1,'Engine') The
current auto_mobile parts is : {2: 'Clutch', 3: 'Gearbox', 'four': 'chassis'}
Is2availableinautomobileparts True
Result:
Thusthepythonprogramtoimplementautomobileusingdictionariesis executed
andverified. .
andverified. .
Ex : 5.3
Elementsofacivil structure
Date:
Aim:
Step1: Starttheprogram
Step2:Createaemptydictionaryusing{} Step
3: Create a dictionary using dict().
Step4:To accessthevaluein thedictionary indexingis applied.
Step5:adding[key]withvaluetoadictionaryusingindexingoperation.. Step 6:
A copy of original dictionary is used by copy ().
Step7: Thelength ofthedictionary is by len().
Step8:Printthevaluesofthedictionarybyusingforloop Step 9:
Stop the program
Program:
civil_ele={}
print(civil_ele)
civil_ele=dict([(1,"Beam"),(2,"Plate")])
print("theelementsofcivilstructureare",civil_ele)
print(" the value for key 1 is :",civil_ele[1])
civil_ele['three']='concrete'
print(civil_ele)
new=civil_ele.copy()
print(" The copy of civil_ele",new)
print("Thelengthis",len(civil_ele)) for
i in civil_ele:
print(civil_ele[i])
.
OUTPUT:
{}
theelementsofcivilstructureare{1:'Beam',2:'Plate'} the
value for key 1 is : Beam
{1:'Beam',2:'Plate','three':'concrete'}
Thecopyofcivil_ele{1:'Beam',2:'Plate','three':'concrete'} The
length is3
Beam
Plate
Concrete
Result:
Thusthepythonprogramtoimplement elementsofacivilstructure using
dictionariesisexecutedand verified.
.
Ex : 6.1
GCD ofgiven numbers using Euclid's Algorithm.
Date:
Aim:
TowriteapythonprogramtofindgcdofgivennumbersusingEuclidsalgorithm.
Algorithm:
Step1: Starttheprogram.
Step 2: Read the values of a and b as positive integers in function call gcd(a,b).
Step3:recursivelyfunctioncallgcd(a,b)willbecomputedin(b,a%b)ifb!=0. Step 4: if
b is equal to 0 return a.
Step 5: Print the result.
Step6:Stoptheprogram.
Program:
defgcd(a,b):
if(b==0):
returna
else:
return gcd(b, a % b)
a=int(input("Enterthevalueofa"))
b=int(input("Enterthevalueofb"))
result=gcd(a,b)
print("Thegreatest common divisor is",result)
Output:
Enter the value of a 24
Enterthevalue of b 54
Thegreatest commondivisor is 6
Result:
Thusthepythonprogram tofindgcdofgivennumbersusingEuclid’smethodisexecutedandthe
resultsareverified. .
resultsareverified. .
Ex : 6.2
Squarerootofagivennumberusingnewtonsmethod.
Date:
Aim:
Towriteapython programtofindto findsquarerootofagivennumberusingnewtons method.
Algorithm:
Step1: Starttheprogram.
Step2:Readthevalueofn,nbeingapositiveintegerinthefunctionnewtonSqrt(n) Step 3: Let
approx = 0.5 * n
Step4: Letbetter=0.5 *(apporx+n/approx)
Step5:Repeatthefollowingstepsuntilbetterequalstoapprox Step
5.1: Let approx = better
Step5.2: Letbetter=0.5*(apporx+n/approx)
Step6:Returnthevalueapproxasthesquarerootofthegivennumbern Step 7:
Print the result.
Step 8: Stop theprogram.
Program:
defnewtonSqrt(n):
approx=0.5 * n
better=0.5*(approx+n/approx)
while(better != approx):
approx=better
better=0.5*(approx+n/approx)
return approx
n=int(input("Enterthenumber"))
result=newtonSqrt(n)
print("TheSquare root for thegiven number is",result)
.
OUTPUT:
Enterthenumber25
TheSquareroot forthe given number is 5.0
Result:
Thusthe python programto find squareroot ofgivennumberusing newtonsmethod is executed and
theresultsareverified. .
Ex : 6.3
Factorialofanumberusingfunctions
Date:
Aim:
Towriteapythonprogramtofindthefactorialof agivennumberbyusingfunctions.
Algorithm:
Step1: Starttheprogram.
Step2:Readthevalueofn aspositiveintegersinfunctioncall factorial(n).
Step3:ifnisnotequaltozero,recursivelyfunctioncallfactorialwillbecomputedasn*
factorial(n-1) and return the value of n.
Step4:ifnisequalto0,returnthevalueas1 Step
5: Print the result.
Step 6: Stop theprogram.
Program:
deffactorial(n):
if n==0:
return1
else:
returnn*factorial(n-1)
n=int(input("Inputanumbertocomputethefactiorial:")) print(factorial(n)
OUTPUT:
Inputanumbertocomputethefactorial:5 120
Result:
Thusthe pythonprogramtofind thefactorial ofa givennumber by using
functionsisexecutedandtheresultsareverified. .
Ex : 6.4
largest numberina listusing functions
Date:
Aim:
Towriteapython programto find thelargestnumber in thelist.
Algorithm:
Step1: Starttheprogram.
Step2:Readthelimitofthelistasn. Step
3: Read n elements into thelist. Step
4: Let large = list[0]
Step5:Executeforloopi=1tonandrepeatthefollowingstepsforthevalueofnuntilthe condition
becomes false.
Step5.1:ifnextelementofthelist>largethen Step
5.1.1: large = element of the list
Step6:Printthelargevalue.
Step 7: Stop the program.
Program:
deflargest(n):
list=[]
print("Enterlistelementsonebyone") for i
in range(0,n):
x=int(input())
list.append(x)
print("Thelistelementsare")
print(list)
large=list[0]
foriinrange(1,n):
if(list[i]>large):
large=list[i]
print("Thelargestelementinthelistis",large)
n=int(input("Enter the limit"))
largest(n)
.
OUTPUT:
Enterthe limit5
Enterlistelementsonebyone 10
20
30
40
50
Thelistelementsare
[10, 20, 30, 40, 50]
Thelargest element inthe list is 50
Result:
Thusthe pythonprogramto findthelargest numberin thelist byusing functions
.
isexecuted andtheresultsare verified.
Ex : 6.5
Areaof shapes
Date:
Aim:
Towriteapythonprogramforareaof shapeusingfunctions.
Algorithm:
Step1: Starttheprogram.
Step2:Read thevalueof landb aspositiveintegers infunctioncall rect(l,b).
Step3:Recursivelycallfunction(rect)willbecomputedasx*yandreturntheresulttothe function call
rect(l,b).
Step4: Printareaofthe rectangle.
Step5:Readthevalue ofnumaspositive integersinfunctioncall circle(num).
Step6:Recursivelycallthefunctioncircle)willbecomputedasPI*(r*r)andreturnthe result to the
function callcircle(num).
Step7: Printareaofthe circle.
Step8:Readthevaluesin functioncalltriangleasaparameters.
Step9:Recursivelycall(triangle)willbecomputedwitha,b,casaparameterandprinttheresult. Step 10:
Read the values as positive integers in function call parallelogram(base,height).
Step11:Recursivelycall(parallelogram)willbecomputedasa*bandreturntheresulttothe function call
parallelogram(Base, Height).
Step12:Printareaof
parallelogram.
Step 13: Stop theprogram.
.
Program:
defrect(x,y):
return x*y
defcircle(r):
PI=3.142
return PI * (r*r)
deftriangle(a,b,c):
Perimeter=a+b+c s =
(a + b + c) / 2
Area=math.sqrt((s*(s-a)*(s-b)*(s-c)))
print("ThePerimeterofTriangle=%.2f"%Perimeter)
print(" The Semi Perimeter of Triangle = %.2f" %s)
print(" The Area of a Triangle is %0.2f" %Area)
defparallelogram(a,b):
return a * b;
#Pythonprogramtocomputeareaofrectangle l=
int(input(" Enter thelength ofrectangle: "))
b=int(input("Enterthebreadthofrectangle:")) a =
rect(l,b)
print("Area=",a)
# Python program to find Area of a circle
num=float(input("Enterrvalueofcircle:"))
print("Area is %.6f" % circle(num))
#pythonprogramtocomputeareaoftriangle import
math
triangle(6,7,8)
#PythonProgramtofindareaofParallelogram Base
= float(input("Enter the Base : "))
Height=float(input("EntertheHeight:"))
Area =parallelogram(Base, Height)
print("TheAreaof aParallelogram =%.3f"%Area)
.
Output:
Area = 6
Enterrvalueofcircle:2
Area is 12.568000
ThePerimeterof Triangle=21.00
TheSemiPerimeterofTriangle=10.50 The
EntertheHeight:5
TheAreaofaParallelogram= 10.000
Result:
Thusthepythonprogramforareaof shapeusingfunctions isexecutedandthe
resultsareverified
.
Ex : 7.1
Date: Reverseofastring
Aim:
To writeapython program forreversing a string..
Algorithm:
Step1: Starttheprogram.
Step2:Readthevalueofastringvaluebyusingfunctioncallreversed_string. Step 3: if
len(text)==1 return text.
Step 4: else return
reversed_string(text[1:])+text[:1].
Step 5: Print a
Step 6: Stop the program
Program:
defreversed_string(text):
if len(text) == 1:
returntext
returnreversed_string(text[1:])+text[:1]
a=reversed_string("Hello, World!")
print(a)
Output:
dlroW ,olleH
Result:
Thusthepythonprogramforreversinga.stringisexecutedandtheresultsare
verified.
Thusthepythonprogramforreversinga.stringisexecutedandtheresultsare
verified.
Ex : 7.2
Palindromeof a string
Date:
Aim:
Towriteapython program forpalindromeofastring.
Algorithm:
Step1: Starttheprogram.
Step 2: Read the value of a string value by using input method.
Step 3: if string==string[::-1], print “ the string is palindrome ”.
Step 4: else print “ Not a palindrome ”.
Step 5: Stop theprogram
Program:
string=input(("Enterastring:"))
if(string==string[::-1]):
print("Thestringisapalindrome")
else:
print("Not apalindrome")
Output:
Enter a string: madam
Thestringisapalindrome
Enter a string: nice
Not apalindrome
Result:
Thusthe pythonprogramforpalindromeofastring is executedand theresults
areverified. .
areverified. .
Ex :7.3
Charactercountofa string
Date:
Aim:
Towriteapythonprogram forcountingthe charactersof string.
Algorithm:
Step1:Starttheprogram.
Step 2: Define a string.
Step2:Defineandinitializeavariablecountto 0.
Step3:Iteratethroughthestringtilltheendandforeachcharacterexceptspaces,increment the
count by 1.
Step4:To avoidcounting thespacescheck thecondition i.e.string[i] !=''.
Step5:Stoptheprogram.
Program:
a=input("enterthe
string")count= 0;
#Countseachcharacterexcept
space for i in range(0, len(a)):
if(a[i]!=''):
count=count+ 1;
#Displaysthetotalnumberofcharacterspresentinthegivenstring
print("Total number of characters in a string: " + str(count));
Output:
enterthe string hai
Totalnumberof charactersin astring: 3
Aim:
Towriteapython program forreplacing thecharacters of a string.
Algorithm:
Step1:Starttheprogram. Step
2: Define a string.
Step3:Determinethecharacter'ch'throughwhichspecificcharacterneedtobereplaced. Step 4:
Use replace function to replace specific character with 'ch' character.
Step5:Stoptheprogram.
Program:
string="Onceinabluemoon" ch
= 'o'
#Replacehwithspecificcharacterch string
= string.replace(ch,'h')
print("Stringafterreplacingwithgivencharacter:")
print(string)
Output:
Stringafterreplacingwithgiven character:
Once in a blue mhhn
Result:
Thusthepython programforreplacingthegivencharactersofstringis executed
andtheresultsareverified.
60
Ex :8.1
Convertlist in toaSeries using pandas
Date:
Aim:
Towriteapython program forconverting list in to a Series.
Algorithm:
Program:
#Tousepandasfirstwehavetoimportpandas import
pandas as pd
#Herepdjustaobjectofpandas
#Defining a List
A=['a','b','c','d','e']
#Convertingintoaseries
df=pd.Series(A)print(df)
Output:
0 a
1 b
2 c
3 d
4 e
dtype: object
Result:
Thusthepythonprogramforconvertinglistintoaseriesisexecuted and the
results are verified.
61
Ex :8.2
Findingtheelementsofa givenarrayiszerousing numpy
Date:
Aim:
Towriteapython programfortesting whethernoneof theelements of agiven array iszero.
Algorithm:
Program:
import numpy as np
#Arraywithoutzerovalue x
= np.array([1, 2, 3, 4,])
print("Original array:")
print(x)
print("Testifnoneoftheelementsofthesaidarrayiszero:")
print(np.all(x))
#Array with zero value
x=np.array([0,1,2,3])
print("Original array:")
print(x)
print("Testifnoneoftheelementsofthesaidarrayiszero:")
print(np.all(x))
Output:
Originalarray:
[1 2 34]
Testif noneof the elementsof thesaidarray is zero:
True
Originalarray:
[0 1 23]
Testifnoneoftheelements ofthesaid arrayis zero:
False
Result:
Thusthe pythonprogramfortesting whethernone of theelements ofagiven arrayis zerois
62
executed andtheresultsareverified.
Ex :8.3
Generatea simple graph usingmatplotlib
Date:
Aim:
Towriteapython programforgenerating asimplegraph using matplotlib.
Algorithm:
Step1: Starttheprogram.
Step2:frommatplotlibimportpyplotlibaray
Step 3: Create a object as pltfor pyplot
Step4:Useplotfunctiontoplotthegivenvalues Step
5:Plot the result using show function
Step 6: Stop theprogram.
Program:
frommatplotlibimportpyplotasplt
#Plotting to our canvas plt.plot([1,2,3],
[4,5,1])
#Showingwhatweplotted
plt.show()
Output:
Result:
Thusthepythonprogramforgeneratingasimplegraphusingmatplotlibzeroisexecuted and the
results are verified.
63
Ex :8.4
Solvetrigonometricproblemsusingscipy
Date:
Aim:
Towriteapython programforfinding theexponents and solve trigonometricproblemsusing
scipy.
Algorithm:
Step1: Starttheprogram.
Step2:fromscipy libarayimport special function
Step3:Useexponent,sin,cosfunctionstoperformscientificcalculatins Step
5:Plot the result.
Step 6: Stop theprogram.
Program:
fromscipyimportspecial a
= special.exp10(3)
print(a)
b=special.exp2(3)
print(b)
c=special.sindg(90)
print(c)
d=special.cosdg(45)
print(d)
Output:
1000.0
8.0
1.0
0.707106781187
Result:
Thusthepythonprogram forfindingtheexponentsandsolvetrigonometricproblemsusing scipy
is executed and the results are verified.
64
Ex :9.1
Copytext from onefileto another
Date:
Aim:
TowriteaPythonprogram for copyingtext fromonefiletoanother.
Algorithm:
Step 1 :Start
Step2:Create filenamedfile.txtandwritesomedatainto it.
Step3 :Create afilename sample.txtto copy thecontentsof thefile
Step4 :Thefilefile.txtis openedusingthe open()functionusing the fstream.
Step5:Anotherfilesample.txtis openedusingtheopen()functioninthewritemodeusingthe f1 stream.
Step6:Eachlineinthefileisiteratedoverusingaforloop(intheinputstream). Step 7 :Each
of the iterated lines is written into the output file.
Step 8 :Stop
Program:
withopen("file.txt")asf:
withopen("sample.txt","w")asf1:
for line in f:
f1.write(line)
65
Output:
Result:
Thusthepythonprogram forcopyingtextfromone fileto anotherisexecutedandtheresults
areverified.
66
Ex : 9.2
CommandLineArguments(WordCount)
Date:
Aim:
TowriteaPython program forcommand linearguments.
Algorithm:
Step1: Start
Step2:Importthepackagesys
Step3:Gettheargumentsincommandlineprompt
Step4:Printthenumberofargumentsinthecommandlinebyusinglen(sys.argv)function Step5:
Print the arguments using str(sys.argv ) function
Step6: Stop
Program:
import sys
print('Numberofarguments:',len(sys.argv),'arguments.')
print('Argument List:',str(sys.argv))
Stepsfor execution:
OpenWindowscommandpromptbytypingcmdinstartupmenu C:\
Users\admin>cd..
C:\Users>cd..
C:\>cd Portable Python 3.2.5.1 C:\
PortablePython3.2.5.1>cdApp
C:\PortablePython3.2.5.1\App>python.execmd.pyarg1arg2 arg3
Or
C:\PortablePython3.2.5.1\App>pythoncmd.pyarg1arg2arg3
Output:
Number of arguments: 4 arguments.
ArgumentList:['cmd.py','arg1','arg2','arg3']
Result:
ThusthePythonprogramforcommandlineargumentsisexecutedsuccessfullyandthe output is
verified.
67
Ex :9.3
Findthe longestword(Filehandling)
Date:
Aim:
TowriteaPythonprogram for findingthelongest wordsusing file handling concepts.
Algorithm:
Program:
#Openingfileinreadingmode
file=open("file.txt", 'r')
#Converting in a list
print("Listofwordsinthefile")
words=file.read().split()
print(words)
#Selectingmaximumlengthword max_len
= max(words, key=len)
print("WordwithmaximumLengthis",max_len) for i
in max_len:
iflen(i)==max_len:
print(i)
Output:
['hai','this','is','parvathy','how','are','you','all','read','well','all','best','for','university',
'exams.']
Result:
ThusthePythonprogramfindingthelongestwordsusingfilehandlingconceptsisexecuted successfully
and the output is verified.
68
Ex :10.1
Date: Dividebyzeroerror–ExceptionHanding
Aim:
TowriteaPython program for finding divideby zero error.
Algorithm:
Program:
try:
num1 = int(input("Enter First Number: "))
num2=int(input("EnterSecondNumber:"))
result = num1 / num2
print(result)
exceptValueErrorase:
print("InvalidInputPleaseInputInteger...") except
ZeroDivisionError as e:
print(e)
Output:
EnterFirstNumber:12.5
InvalidInputPleaseInput Integer...
Result:
ThusthePythonprogramforfindingdividebyzeroerrorisexecutedsuccessfullyandthe output is
verified.
69
Ex :10.2
Date: Voter’sagevalidity
Aim:
TowriteaPython programforvalidatingvoter’sage.
Algorithm:
Step1:Starttheprogram
Step2: Accepttheageoftheperson.
Step3:Ifageisgreaterthanorequalto18,thendisplay'Youareeligibletovote'. Step 4: If
age is less than 18, then display 'You are not eligible to vote'.
Step5:Iftheentereddataisnotinteger,throwanexceptionvalueerror. Step 6: :
If the entered data is not proper, throw an IOError exception Step 7: If no
exception is there, return the result.
Step 8: Stop theprogram.
Program:
defmain():
#singletrystatementcanhavemultipleexceptstatements. try:
age=int(input("Enteryourage")) if
age>18:
print("'Youareeligibletovote'")
else:
print("'Youarenoteligibletovote'")
except ValueError:
print("agemustbeavalidnumber")
except IOError:
print("Entercorrectvalue")
#genericexceptclause,whichhandlesanyexception. except:
print("AnErroroccured")
main()
70
Output:
Enteryourage20.3
agemust beavalid number
Enteryourage35
Eligible to vote
Result:
ThusthePythonprogramfor validatingvoter’sage isexecutedsuccessfullyandtheoutputis verified.
71
Ex :10.2
Date: Studentmarkrangevalidation
Aim:
Towriteapython program forstudent mark rangevalidation
Algorithm:
Step1: Starttheprogram
Step2:Get theinputs fromtheusers.
Step3:Iftheentereddataisnotinteger,throwanexception. Step 4:
If no exception is there, return the result.
Step 5: Stop theprogram.
Program:
defmain():
try:
mark=int(input("Enteryourmark:"))
if(mark>=50 and mark<101):
print("Youhavepassed")
else:
print("Youhavefailed")
except ValueError:
print("Itmustbeavalidnumber") except
IOError:
print("Entercorrectvalidnumber")
except:
print("anerroroccured")
main()
72
Output:
Enteryourmark:50
You have passed
Enter your mark:r
Itmustbeavalidnumber
Enter your mark:0
Youhave failed
Result:
Thusthepythonprogramforstudent markrangevalidationisexecutedandverified.
73
Ex :11
ExploringPygametool.
Date:
Pygame:
Stepsforinstallingpygame package:
1. OpenWindowscommandpromptbytypingcmdinstartup menu
2. C:\Users\admin>cd..
3. C:\Users>cd..
4. C:\>cdPortablePython3.2.5.1
5. C:\PortablePython3.2.5.1>py-mpipinstall-Upygame–user
OnlineExecutionProcedure:
1. Copythisurl:https://trinket.io/features/pygametoyourbrowserandopen
pygame interpreter
2. Removethesourcecodeinmain.pyandcopythebelowsourcecodeto
main.py
3. ClicktheRunbuttonto execute.
74
Ex : 12.1
SimulateBouncingBallUsing Pygame
Date:
Aim:
TowriteaPython program tosimulate bouncingball in pygame.
Algorithm:
Step1: Start
Step2:Importthenecessarypackages
Step3:Initializetheheight,widthandspeedinwhichtheballbounce Step4:Set
Step5:Loadtheballimage
Step4:Movetheballfromlefttoright Step5:
Stop
Program:
importsys,pygame
pygame.init()
size=width,height=700,300
speed = [1, 1]
background=255,255,255
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncingball")
ball=pygame.image.load("'C:\\Users\\parvathys\\Downloads\\ball1.png") ballrect
= ball.get_rect()
while 1:
foreventin pygame.event.get():
ifevent.type==pygame.QUIT:sys.exit()
75
ballrect= ballrect.move(speed)
ifballrect.left<0orballrect.right>width: speed[0]
= -speed[0]
ifballrect.top<0orballrect.bottom>height:
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball,ballrect)
pygame.display.flip()
Output:
Result:
76
Ex : 12.2
CarRace
Date:
Aim:
TowriteaPythonprogram tosimulate car raceinpygame.
Algorithm:
Step1: Start
Step2:Importthenecessarypackages
Step3:Initializetheheight,widthofthescreenandspeedinwhichthecarcanrace. Step4:Set the
screen mode
Step5:Loadtherequiedimageslikeracingbeast,logo,fourdifferentcarimages Step4:
Move the car on the race track
Step5: Stop
Program:
import pygame
pygame.init()#initializesthePygame
frompygame.localsimport*#importallmodulesfromPygame screen
= pygame.display.set_mode((798,1000))
#changing title of the game window
pygame.display.set_caption('RacingBeast')
#changing the logo
logo=pygame.image.load('C:\\Users\\parvathys\\Downloads\\cargame/logo.png')
pygame.display.set_icon(logo)
#definingourgameloopfunction def
gameloop():
#settingbackground image
bg=pygame.image.load(''C:\\Users\\parvathys\\Downloads\\cargame/bg.png') #
setting our player
maincar=pygame.image.load(''C:\\Users\\parvathys\\Downloads\\cargame\car.png')
maincarX = 100
maincarY=495
maincarX_change=0
maincarY_change=0
77
#othercars
car1=pygame.image.load(''C:\\Users\\parvathys\\Downloads\\cargame\car1.png')
car2=pygame.image.load(''C:\\Users\\parvathys\\Downloads\\cargame\car2.png')
car3=pygame.image.load(''C:\\Users\\parvathys\\Downloads\\cargame\car3.png')
run = True
whilerun:
for event in
pygame.event.get():ifevent.typ
e==pygame.QUIT:
run = False
ifevent.type==pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
maincarX_change+=5
ifevent.key==pygame.K_LEFT:
maincarX_change -= 5
ifevent.key==pygame.K_UP:
maincarY_change -= 5
ifevent.key==pygame.K_DOWN:
maincarY_change += 5
#CHANGINGCOLORWITHRGBVALUE,RGB=RED,GREEN,BLUE
screen.fill((0,0,0))
#displayingthebackgroundimage
screen.blit(bg,(0,0))
#displaying our main car screen.blit(maincar,
(maincarX,maincarY)) #displaing other cars
screen.blit(car1,(200,100)) screen.blit(car2,
(300,100)) screen.blit(car3,(400,100))
#updatingthe values
maincarX+=maincarX_change
maincarY +=maincarY_change
pygame.display.update()
gameloop()
78
Output:
Result:
ThusthePythonprogramtosimulatecarraceusingpygameisexecutedsuccessfullyandthe output is
verified.
79