0% found this document useful (0 votes)
12 views38 pages

Ge3171 PSPP Lab

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)
12 views38 pages

Ge3171 PSPP Lab

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
You are on page 1/ 38

Accr

edi
tedbyNAAC|UGCRecogni
zed2(
f)Status|
ApprovedbyAICTE|Af
fi
li
atedt
o
AnnaUni
ver
sit
y|AnI
SO9001:2008Cert
if
iedInst
it
uti
on.

DEPARTMENTOFCOMPUTERSCI
ENCEANDENGI
NEERI
NG

ACADEMI
CYEAR2021–2022

FI
RSTSEMESTER

GE3171–PROBLEM SOLVI
NGANDPYTHONPROGRAMMI
NGLABORATORY

NAME :
………………………………………………………

REG.
NO :
………………………………………….
…………….

SECTI
ON :
…………………………………………………….
.
GE3171 PROBLEM SOLVI
NGANDPYTHONPROGRAMMI
NGLABORATORY

COURSEOBJECTI
VES:

 Tounderst
andt heproblem sol
vi
ngappr oaches.
 Tol
earnthebasi cprogrammingconst ructsinPython.
 Topract
icev ar
iouscomput i
ngstrategiesforPython-basedsol
uti
onst
oreal
wor
ldproblems.
 TousePy t
hondat astruct
ures-li
sts,tuples,di
cti
onaries.
 Todoinput/outputwit
hf i
lesi
nPy thon.

LI
STOFPROGRAMS:

1.Solvi
ngsi mpl ereal l
if
epr obl emsusi ngf lowchar t:
a.Dev elopaf l
owchar tf orElect
r i
cit
yBi l
ling
b.Dev elopaf l
owchar tf orRetailShopBi l
li
ng
c.Dev elopaf l
owchar tf orSineSer i
es
d.Dev elopaf l
owchar tf orcomput ingEl ectrical Curr
enti nThr eePhaseAC
Circuit
e.Dev elopaf l
owchar tf orfi
ndingwei ghtofaSt eelBar
2.SimpleSt atement sandExpr essi
ons:
a.Wr i
teaPy t
honpr ogr am toexchanget hev al uesoftwov ari
abl es.
b.Wr i
teaPy t
honpr ogr am tocirculat et hev aluesofnv ar i
ables.
c.Wr i
teaPy t
honpr ogr am tof i
ndt hedi stancebet weent wopoi nts.
3.Conditi
onal sandI terati
vel oops:
a.Wr i
teaPy t
honpr ogr am forNumberSer i
es.
b.Wr i
teaPy t
honpr ogr am forNumberPat t
er n.
c.Wr i
teaPy t
honpr ogr am forPy rami dPat tern.
4.Operati
onsofLi standTupl es:
a.Wr i
teaPy t
honpr ogr am toimpl ementt het upl eoperationsf orlibr ary
details
b.Wr i
teaPy t
honpr ogr am toimpl ementt het upl eoperationsf ormat er
ial
s
requiredforconst r
uct ionofabui lding.
c.Wr i
teaPy t
honpr ogr am toimpl ementt hel istoperati
onsf orcomponent s
ofacar .
5.SetsandDi cti
onaries:
a.Wr i
teaPy t
honpr ogr am toimpl ementt heSetoper ationsf orpr ogr ammi ng
l
anguagedet ail
s.
b.Wr i
teaPy t
honpr ogr am toimpl ementt heDi cti
onaryoper ationsf orthe
component sofanaut omobile.
6.Functi
ons:
a.Wr i
teaPy t
honpr ogr am tof i
ndt hef act orial ofanumberusi ngaf unct i
on.
b.Wr i
teaPy thonpr ogr am tof i
ndt hel argestnumberi nt helistusi ng
funct i
ons.
c.Wr i
teaPy t
honpr ogr am tocal culatet hear eaofdi f
ferentshapesusi ng
functi
ons.
7.Str
ings:
WriteaPy thonpr ogram toimplementst ringoper at
ionslikereversi
ngthe
str
ing,palindrome, charactercountandr epl
acingchar acter.
8.Pandas, Numpy ,Mat pl
otli
b&Sci Py:
a.I mplement ingprogramsusi ngwr i
ttenmodul esandPy t
honSt andard
Libr
aries
b.Dr awl i
neandbarchar tsusingMat pl
otli
b
9.Fil
ehandl i
ng:
WriteaPy thonpr ogram toimplementcopyf r
om onef il
et oanother,word
countandf i
ndt helongestwordusi ngf i
lehandling.
10.
Exceptionhandl ing:
a.Wr i
teaPy thonpr ogram toi
mpl ementDi vi
debyZer oer rorusingExcepti
on
handli
ng.
b.Wr i
teaPy thonpr ogram tocheckt hev oter’
sagev ali
dity.
11.
PygameTool :
Explori
ngPy gameTool
12.
GameAct i
vit
yusi ngPy game:
a.Dev elopaBounci ngBallgameact iv i
tyusingPy game.
b.Dev elopaCarRacegameact iv
ityusi ngPy game.

OUTCOMES:

Oncomplet
ionofthecour se,st
udentswi l
lbeabl eto:
CO1:Developalgor
ithmicsolut
ionst osimpl ecomput ationalprobl
ems
CO2:Developandexecut esimplePy t
honpr ogr
ams.
CO3:I
mpl ementprogramsi nPythonusi ngcondi t
ional sandl oopsforsol
vi
ng
pr
obl
ems.
CO4:Deployfuncti
onst odecomposeaPy thonprogr am.
CO5:Processcompounddat ausingPy thondatast ruct ures.
CO6:Uti
li
zePy t
honpackagesi ndev elopingsoftwareappl icat
ions.
CONTENTPAGE

EX. PAGE
DATE PARTI
CULARS MARKS SI
GN
NO. NO.
19.
11.
202 Dev
elopaf
lowchar
tforEl
ect
ri
cit
yBi
l
li
ng
1a)
1
23.
11.
202
1b) Dev
elopaf
lowchar
tforRet
ail
ShopBi
l
li
ng
1
26.
11.
202
1c) Dev
elopaf
lowchar
tforSi
neSer
ies
1
30.
11.
202 Dev elopaf lowchar tforfindi
ngwei ghtofa
1d)
1 Steel Bar
03.
12.
202 Dev elopaf lowchar tforcomput ing
1e)
1 ElectricalCurrenti
nThr eePhaseACCi rcui
t
07.
12.
202 Py t
honpr ogr am toexchanget hev aluesof
2a)
1 twov ar i
ables.
10.
12.
202 Py t
honpr ogr am tocirculatethev aluesofn
2b)
1 variables.
14.
12.
202 Py t
honpr ogr am tof i
ndt hedistance
2c)
1 betweent wopoi nts.
21.
12.
202
3a) Py
thonpr
ogr
am f
orNumberSer
ies.
1
24.
12.
202
3b) Py
thonpr
ogr
am f
orNumberPat
ter
n.
1
28.
12.
202
3c) Py
thonpr
ogr
am f
orPy
rami
dPat
ter
n.
1
31.
12.
202 Pythonpr ogr am toimpl ementt hetupl
e
4a)
1 operationsf orl
ibrarydet ails
Pythonpr ogr am toimpl ementt hetupl
e
04.
01.
202
4b) operationsf ormat eri
alsr equiredfor
2
constructionofabui l
ding.
01.
02.
202 Pythonpr ogr am toimpl ementt heli
st
4c)
2 operationsf orcomponent sofacar .
Pythonpr ogr am toimpl ementt heSet
04.
02.
202
5a) operationsf orprogrammi ngl anguage
2
detai
ls.
Pythonpr ogr am toimpl ementt he
04.
02.
202
5b) Dicti
onar yoperat i
onsf ort hecomponent s
2
ofanaut omobi le
08.
02.
202 Pythonpr ogr am tofi
ndt hef actori
alofa
6a)
2 numberusi ngaf unction.
08.
02.
202 Pythonpr ogr am tofi
ndt helargestnumber
6b)
2 i
nt helistusingf uncti
on
11.02.202 Pythonpr ogram tocal culatet hear eaof
6c)
2 dif
fer entshapesusi ngf unct i
on
Pythonpr ogram toimpl ementst ring
12.02.202
7 oper ationsl i
kerev erse,pal indrome,
2
char actercountandr eplaci ngchar acter
15.02.202 Impl ement i
ngprogr amsusi ngwr itten
8a)
2 modul esandPy thonSt andar dLibr ari
es
15.02.202
8b) Drawl i
neandbarchar tsusi ngMat plotl
i
b
2
Pythonpr ogram toimpl ementcopyf rom
18.02.202
9 onef i
let oanother ,wor dcountandf i
ndthe
2
l
ongestwor dusingf il
ehandl ing.
22.02.202 Pythonpr ogram toimpl ementDi v i
deby
10a)
2 Zeroer rorusingExcept ionhandl ing.
23.02.202 Pythonpr ogram tocheckt hev ot
er ’
sage
10b)
2 val
idi t
y
24.02.202
11 Explor i
ngPy gameTool
2
25.02.202 Dev elopaBounci ngBal l gameact ivit
y
12a)
2 usingPy game
Dev elopaCarRacegameact i
vit
yusi ng
12b) 26.02.22
Pygame
CONTENTPAGE

EX. PAGE
DATE PARTI
CULARS MARKS SI
GN
NO. NO.
1. a) Dev
elopaf
lowchar
tforEl
ect
ri
ci
tyBi
l
li
ng

St
art

ReadSt
art
_Uni
t,

Tot
al_
Uni
t=End_
Uni
t-
Star
t_Uni
t

If
Tot
al_Uni
t
Amount=
<=
100 Tot
al_
uni
t*1.
00

If
Tot
al_Uni
t Amount=
<=
200 Tot
al_
uni
t*1.
50

Amount=
Tot
al_
uni
t*2.
00

Pr
intTot
al_
Uni
t,Amount

St
op
1. b) Dev
elopaf
lowchar
tforShopBi
l
li
ng

St
art

Readn

I
=1,
Tot
al=0

I
f
i
<=n

ReadIt
em_Name,
Qty,
Unit
_Pr
ice

Rat
e=Uni
t_pr
ice*Qt
y

Pri
ntI
tem_Name,
Qt
y,Unit
_pr
ice,

Tot
al=Tot
al+Rat
e

i
=i+1

Pr
intTot
al

St
op
1. c) Dev
elopaf
lowchar
tforsi
nser
ies

St
art

x3 x5
si
nx=x- + - …
Readx,
n 3! 5!
∞ n
(-
1) 2n+1
i
=1,
y=x

n=0
(
2n+1)
!
x

x=x*
3.1415/
180

t
=x,
sum=x

I
fi<=n
No

t=(
(-
1)*t*x*x)/
Yes
(
(2*i
)*(
2*i
+1)
)

sum =sum +t

i
=i+1

Pr
int“
Sin”+(
y)

Pr
int“
is”+sum

St
op
1. d) Dev
elopaf
lowchar
tforf
indi
ngwei
ghtofast
eel
bar
.

St
art

D2
W= *L
ReadD,
L 162.
2

W =(
D*D)/162.
2*L

Pr
int
W

St
op
1. e) Dev
elopaf
lowchar
ttocomput
ecur
renti
nthr
eephaseACci
rcui
t.

St
art

Readt
hree_
phase_
power
,VLL,
pf

VLN=VLL/ 3

si
ngl
e_phase_
power=t
hree_
power/3

kVA=si
ngl
e_power/pf

VA=kVA*1000

cur
rent=VA/VLN

pr
intcur
rent

st
op
EXPTNO:
Exchanget
hev
aluesoft
wov
ari
abl
es
DATE:

Ai
m:
Towr
it
eapy
thonf
orexchanget
hev
aluesoft
wov
ari
abl
es

Al
gori
thm:
St
ep1:St
arttheprogram
St
ep2:Gettheval
uesf r
om user
St
ep3:Swapbotht hevaluesusi
ngt
empor
aryv
ari
abl
es
St
ep4:Pri
nttheswappedout put
St
ep5:St
opt hepr
ogr am

Pr
ogr
am:
/
/exchanget heval
ueoftwov ari
abl
es
pri
nt(
“entertheval
ueforA:”
)
a=int
(i
nput (
))
pri
nt(
“entertheval
ueforB:”
)
b=int
(i
nput (
))
pri
nt(
“beforeexchangi
ngvalues”)
pri
nt(
“A=”,a,
”B=”
,b)
temp=a
a=b
b=temp
pri
nt(
“aft
erExchangingthevalueofvar
iabl
es”
)
pri
nt(
“A=”,a,
”B=”
,b)

Output:
entertheval
ueforA:10
entertheval
ueforB:20
beforeexchangi
ngvaluesA=10B=20
aft
erExchangingthevalueofv
ari
abl
esA=20B=10

Resul
t:
ThusThePy
thonPr
ogr
am ForSwappi
ngTwoVar
iabl
esLoopsWasExecut
edSuccessf
ull
y.
EXPTNO:
Ci
rcul
atet
hev
aluesofnVar
iabl
es
DATE:

Ai
m:
Towr
it
eapy
thonpr
ogr
am f
orci
rcul
atet
hev
aluesofnv
ari
abl
es

Al
gor
it
hm:
Step1:
Startthepr ogr
am.
Step2:
Gett henumberofv al
uesfrom user
.
Step3:
Declar ethearrayvari
abl
e.
Step4:
Gett helistval
uesfrom userandappendit
Step5:
Circulatetheli
stvalusbyusingforl
oop.
Step6:
Printtheci r
cul
atedoutput.
Step7:
Stopt hepr ogr
am.

Pr
ogram:
//ci
rculatethev aluesofnv ariable
no_ of_t
erms=i nt(
input(“
Ent ernumberofv al
ues:
”)
)
li
st 1=[]
forv ali
nr ange( 0,
no_of_terms,1):
element=i nt(i
nput (
“Enterinteger:
”))
l
ist1.append( element )
print(“
Circulati
ngt heelement soflist
”,
li
st1)
forv ali
nr ange( 0,
no_of_term,1)
element=l i
st1.pop(0)
li
st 1.
append( element )
print(l
i
st1)

Output:
Enternumberofval
ues:4
Enteri
nteger:10
Enteri
nteger:20
Enteri
nteger:30
Enteri
nteger:40
Cir
culati
ngtheel
ementsofl
i
st[
10,
20,
30,
40]
[
20,30,
40,
10]
[
30,40,10,
20]
[
40,10,20,
30]
[
10,20,30,
40]

Resul
t:
Thus t
he py
thon pr
ogr
am f
orci
rcul
atet
he v
alues ofn
v
ari
abl
eswasexecut
edsuccessf
ull
y.

EXPTNO: Di
stancebet
weent
wopoi
nts
DATE:

Ai
m:
Towr
it
epy
thonpr
ogr
am f
ordi
stancebet
weent
wopoi
ntsusi
ngbui
l
tinf
unct
ions.

Al
gor
it
hm:

St
ep1:
Starttheprogram.
St
ep2:
Impor tt
hemat hmodul e.
St
ep3:
Gett hefourvaluesfrom user
.
St
ep4:
Calculat
et heDistancebetweent
wopoi
ntsbyusi
ngmat
h.sqr
tbui
l
tinf
unct
ion

St
ep5:
Printt
heDi
stancebet
weent
wopoi
ntout
put
.
St
ep6:
Stopthepr
ogram.

Progr am:
//Distancebet weent wopoi nt
simportmat h
x1=int (
input(“Ent
ert hevaluesf orx1:
”)) y1=i
nt(
input(“
Enter
thev aluesf ory1:”
)) x2=i
nt(
input
(“Ent
ert
heval
uesf orx2:
”))
y 2=int(input(
“Enterthev aluesfory2:
”)
)
di stance=mat h.sqrt(
((x2-x1)**
2)+((
y2-
y1)*
*2))
pr int(
“Thedi stancebet weent wopointsi
s”,
distance)

Out
put
:
Ent
ert
hev al
ueforx1:
2
Ent
ert
hev al
uefory1:
3
Ent
ert
hev al
ueforx2:
5
Ent
ert
hev al
uefory2:
6
Thedi
stancebet
weentwopoi
ntsi
s4.
242

Result
:
Thust
hePy
thonpr
ogr
am f
orDi
stancebet
weent
wopoi
ntswasexecut
edsuccessf
ull
y.

EXPTNO: NumberSer
ies
DATE:

Ai
m:
Towr
it
eapy
thonpr
ogr
am f
orNumberser
iesusi
ngCondi
ti
onal
sandI
ter
ati
vel
oops

Al
gori
thm:
Step1:
Startthepr ogr am
Step2:
Int
ial
izethear rayv ari
abl
es
Step3:
Getthev aluesf rom theuser
Step4:
Checkt her angev aluebyusi
ngforl
oop
Step5:
Processt heNser i
esofnumbersunti
lthel
oopends.
Step6:
Appenedal l t
henumber sonebyone.
Step7Pri
nttheresul t.
Step8:
Stopthepr ogr am.

Pr
ogr
am:
n=int(i
nput("Enteranumber :
"))
a=[]
foriinrange( 1,n+1):
print(i
,sep="",end="")
if
(i<n):
print("+",
sep="",end=""
)
a.append( i
)
pri
nt("=",
sum( a))
pri
nt()

Out
put
Ent
eranumber
:
5
1+2+3+4+5=15

Result
Thust
hepythonpr
ogram forNumberser
iesusi
ngCondi
ti
onal
sandI
ter
ati
ve
loopswereexecut
edsuccessful
ly
.
EXPTNO:
NumberPat
ter
n
DATE:

Ai
m:
Towr
it
eaPy
thonpr
ogr
am f
orNumberPat
ter
nsusi
ngI
ter
ati
vel
oops.

Al
gori
thm:
Step1:St
ar tt
heprogram
Step2:I
niti
ali
zethenumberofr
owv al
ues.
Step3:Checktherangeval
uebyusi
ngforloop.
Step4:Processt
heNumberPatter
nsusingIter
act
ivel
oop.
Step5:Pri
nttheresul
t.
Step6:St
opt heprogr
am.

Program:
nrows=i nt(i
nput(
"Entert
henumberofr
ows"
))
foriinrange(nrows,0,
-1)
:
forjinrange(0,
i+1):
pri
nt(j
,end="")
pri
nt("\
r")
pri
nt(i
-1)
Output:
01234567
0123456
012345
01234
0123
012
01
0

Resul
t:
Thus the Py
thon pr
ogr
am f
orNumberPat
ter
ns usi
ng I
ter
ati
vel
oops wer
e
execut
edsuccessf
ull
y
.

EXPTNO:
Py
rami
dPat
ter
n
DATE:

Ai
m:
Towr
it
eapy
thonpr
ogr
am f
orPy
rami
dpat
ter
nusi
ngI
ter
ati
vel
oops

Al
gori
thm:
Step1:Startthepr ogr am
Step2:I
nitiali
zet hev ari
ables
Step3:Gett hev aluesf r
om theuser
Step4:Checkt her angev al
uebyusingforl
oop.
Step5:Calculatet hespacef orpyrami
dpattern
Step6:Eachi terati
oni ncrementthepat
ternli
ke”unt
ilt
hel
oopsend
Step7:Printthepy ramidpatter
n
Step8:Stopt hePr ogr am

Program:
n=int(
input ("Ent
ernumberofr ows"))
k=n-1
#out erl oopt ohandl enumberofr ows
foriinrange( 0,
n):
#innerl oopt ohandl enumberspaces
#v alueschangi ngacc.t orequir
ement
forjinr ange(0,k) :
print(end="" )
#decr ement i
ngkaf tereachloop
k=k-1
#innerl oopt ohandl enumberofcol umns
#v alueschangi ngacc.t oouterloop
forjinr ange(0,i+1):
#pr intingstar s
print("*",end="")
#endi ngli
neaf tereachr ow
pri
nt("\r")

Output
:
Ent
ernumberofr
ows
5
*
**
***
****
*****
Result
:
ThusthePythonpr
ogr
am f
orPy
rami
dpat
ter
nusi
ngI
ter
ati
vel
oopswer
eexecut
ed
successf
ull
y.
EXPTNO:
Tupl
eOper
ati
onsf
orLi
brar
yDet
ail
s
DATE:

Ai
m:
Towr
it
eapy
thonoper
ati
onf
orl
i
brar
ydet
ail
susi
ngt
upl
es.

Al
gor
it
hm:
St
ep1:Startthepr ogram
St
ep2:I
nitial
izethet upl
evalues
St
ep3:Tot hetupleoper at
ionsuchasindex
,lengt
h,concat
enat
ion,
repet
it
ion,
membershipoper ati
on.
St
ep4:Processt hesl i
ci
ngintheli
brar
ytupl
ev al
ues.
St
ep5:Printalloutputs.
St
ep6:Stopt hepr ogram.

Program:
tupl
e_li
brary
1=( "
deptbooks" ,
"dept j
our nal s",
"uni
v questpaper s")
tupl
e_li
brary
2=( "
compet it
iveExamsgui de" ,
"eBooks" ,"
ejournals")
pri
nt(
"Indexi
ngposi ti
onofl ibrary1:",
tupl e_libr
ary1[1])
pri
nt(
"Number sofComponent sinlibrar yt upl
e1" ,l
en(tuple_li
brary1))
pri
nt(
"Number sofcomponent sinlibraryt uple2" ,
len(tupl
e_ l
ibrary2))
pri
nt(
"Concatenat i
onoft wol ibrarytupl e",tupl
e_ l
ibrary1+tuple_li
brary2)
pri
nt(
"Repetit
ionoft upl
e_library1",
tupl e_ l
ibrary1*2)
pri
nt(
"Member shipoperatoroft uplelibrar y1:",
"ebooks"i ntuple-li
brary1)
pri
nt(
"Member shipoperatoroft uplelibrar y1:"
,"
ebooks"i nt uple_l
ibrary2)
pri
nt(
"Sli
cingoft upl
e_li
brary2" ,
tuple_li
br ary 2[
0:2])

Out
put:
I
ndexingposi ti
onofl i
brary1: dept j
our nals
Numberofcomponent sinl ibraryt uple13
Numberofcomponent sinl ibraryt uple23
Concatenationoft wol ibraryt uples ( ‘
deptbooks’
,‘deptj
ournal
s’
,

uni
vquestpapers’,

compet it
iveExamgui de’,
’ebooks, ”ejournals’
)
Repet i
ti
onoft uple_libr
ar y
1( ‘
dept books’ ,‘dept
jor
nals’
,‘univ
questpaper
s’,
‘deptbooks’,‘
dept j
ournal s’,
uni v
quest papers’
)
Member shipoper atoroft uplelibrary1: False
Member shipoper atorsoft uplelibrary2: True
Sli
cingoft uple_l
ibrary2:( ‘
Compet i
tiveExamgui de’
,’
ebooks’)

Resul
t:
Thus the py
thon t
upl
e oper
ati
on f
or Li
brar
y Det
ail
s was execut
ed
successful
l
y
.
EXPTNO: Tupl
eOper
ati
onsf
orMat
eri
alsRequi
redf
orConst
ruct
ionof
DATE: aBuildi
ng

Ai
m:
Towr
it
eapy
thont
upl
eoper
ati
onsf
orMat
eri
alsr
equi
redf
orconst
ruct
ionofa
bui
l
ding

Al
gor
it
hm:
St
ep1:Startthepr ogram
St
ep2:I
nitial
izethet upl
evalues
St
ep3:Dot hetupl eoperat
ionssuchaslength,
concat
enat
ion,
repet
it
ion,
membershipoper ati
on.
St
ep4:Processt hesl i
ci
ngintheli
brar
ytupleval
ues.
St
ep5:Printalloutputs.
St
ep6:Stopt hepr ogram.

Program:
tupl
e_buil
ding1=(“bri
cks”,
”sand” ,
”cement ”
)
tupl
e_buidi
ng2=( “
til
es”,
”paint”
,’
’wood” )
pri
nt(“I
ndexingpositi
onofbui lding1” ,t
uple_buil
di ng[ 1])
pri
nt(“Number sofComponent si nbui l
dingtuple” ,
len( t
uple_buildi
ng1) )
pri
nt(“Number sofComponent si nbui l
dingtuple2” ,len(t
uple_ buil
ding2))
pri
nt(
“Concatenati
onoft wobui l
dingt uples”,t
upl e_bui l
ding1+t uple_bui
ldi
ng2)
pri
nt(“Repeti
ti
onoft upl
e_building1“.
t uple_bui
lding1* 2)
pri
nt(“Member shi
poper atoroft upl
ebui lding1:”,”pai nt
”int uple_buildi
ng1)
pri
nt(
“Member shipoperatoroft uplebuilding2:
”,”pai nt”i
nt uple_buildi
ng2)
pri
nt(
“Sli
cingoftuple_buil
ding1:”,
tuple_buildi
ng1[ 0:2] )

Output:
I
ndexingpositi
onofb1: sand
Numberofcomponent sinbui l
di ngt upl
e13
Numberofcomponent si nbuildingt uple23
Concatenati
onoftwobui ldingt upl es( ‘
bri
cks’,
sand’
,
’cement’
,’
ti
les’
,
’pai
nt’
,
’wood’
)
Repeti
ti
onoft upl
e_buil
ding1( ‘
br icks’ ,

sand’,
’cement’
,’
bri
cks’
,
’sand’
,’
cement’
)
Member shipoper
atoroft uplebui lding1:False
Member shipoper
atorsoft uplebui l
ding2:True
Sl
ici
ngoft upl
e_buil
ding1: (‘
bricks’ ,
’sand’)

Result
:
Thusthepy
thont
upl
eoper
ati
onsf
orComponent
sofacarwer
eexecut
ed
successful
l
y
EXPTNO:
Li
stOper
ati
onsf
orComponent
sofaCar
DATE:

Ai
m:
Towr
it
eaPy
thonl
i
stoper
ati
onsf
orComponent
sofacar
.

Algorit
hm:
Step1:St
artthepr ogr am
Step2:I
niti
ali
zethel istv al
ues
Step3:Pr
ocessal l t
hel i
stoperat
ionssuchas
l
engt h,
concat
enati
on,repertition,
member ship,operati
ons.
Step4:Sl
icesomeoft hecarcomponentsint
hel
i
st
values.
Step5:Pr
intalloutput s.
Step6:St
opt hepr ogr am.

Program:
l
istcar1=[steeri
ng’,

wheel s’
.’
brake’,
’engi ne’,
’seat s’]
l
istcar2=[“accel
erator”
,”cl
utch”,
”gear ”,”horn”,”indicat or”,”batt
ery
”]
pri
nt(
“indexingofposi t
ionof2i ncarl ist1:”
,li
st _car1[ 2])
pri
nt(
“number sofcomponent sincarl i
st1”,len( l
ist_car 1) )
pri
nt(
“number sofcomponent sincar tl i
st2”,len( l
ist_car 2))
pri
nt(
“concat enati
onoft wocarl ist”,l
ist_car1+l ist_car 2)
pri
nt(
“repet i
ti
onofcarl i
st”,
li
st_car1* 2)
pri
nt(
“member shipoperatorofcar list1:”,
”bat tery”inlist_ car1)
pri
nt(
“member shipoperatorofcar list2:”,
”bat tery”inlist_ car2)
pri
nt(
“sli
cingofcarl ist
1:”,
li
st_car1[0:3])

Out
put
:

i
ndexingposi t
ionof2i ncarli
st1:rake
number sofcomponent sincarli
st15
number sofcomponent sincarli
st26
concatenati
onoft wocarl i
st[‘
steering’,
’wheels’,

brake’,

engine’,‘
seats’,‘
accelarat
or’
,’
clutch’,
’gear’
,’horn’
,’i
ndicat
or’
,
’batt
ery’
]
repeti
ti
onofcarl ist1[‘st
eeri
ng’,‘
wheel s’,‘
brake’,‘
engine’
,‘
seat
s’,‘
steer
ing’
,‘
wheel
s’
,

brake’,‘
engine’,
‘seats’]
member shi
poper atorofcarli
st1:false
member shi
poper atorsofcarli
st2:true
sli
cingofcarlist:[‘
steeri
ng’,
wheels’,
’brake’]

Resul
t:
Thusthepyt
hontupl
eoperat
ionf
orMat
eri
alsr
equi
redf
orconst
ruct
ionofa
bui
ldi
ngwereexecut
edsuccessf
ull
y.
EXPTNO:
Setoper
ati
onsf
orpr
ogr
ammi
ngl
anguagedet
ail
s
DATE:

Aim:
Towri
teapyt
honpr
ogr
am f
ori
mpl
ement
ingt
hepr
ogr
ammi
ngl
anguagedet
ail
s
usi
ngsetoper
ati
on.

Al
gori
thm:
St
ep1:St
arttheprogram.
St
ep2:I
nit
iali
zethesetval
uesfrom user
.
St
ep3:I
mpl ementthesetoper
ationsuchasuni
on,
int
eract
ionandsetdi
ff
erence.
St
ep4:Pr
intallout
puts.
St
ep5:St
opt heprogram.

Pr
ogram:
Set1_l
ang={ “
C”,
”C++”,
”Py
thon”,
”Jav a” }
Set2_l
ang={ “
C”,
”Pyt
hon”,
”.
Net”,
”C#” }
pri
nt(
“Theset 1l
anguageare“,
set1_ lang)
pri
nt(
“Theset 2l
anguageare”
,set2_lang)
pri
nt(
“Unionoftwosetare”,
set1_lang. uni
on(set2_l
ang))
pri
nt(
“I
ntersecti
onoftwosetare”,set 1_l
ang.
intersect
ion(
set
2_lang)
)
pri
nt(
“Dif
ferenceoftwosetare”,
set1_ l
ang.
diff
erence(set
2_l
ang))

Out
put:
Theset 1l
anguageare{‘C’
,’
Java’,
C++’ ,
Python’
}
Theset 2l
anguageare{‘C’
,’
.Net
’,C#,’
’pyt
hon’}
Unionoftwosetare{‘
Net ’
,
Java’,
’C#’,
’Python’
,’
C’,

C++’
}
I
ntersecti
onoftwosetare{ ‘
C’,

Py thon’}
Dif
ferenceoftwoset{‘
C++’,
’Java’}

Resul
t:
Thus the pyt
hon setoper
ati
on f
orpr
ogr
ammi
ng l
anguage det
ail
s was
execut
edsuccessful
l
y..
EXPTNO: Di
cti
onar
yoper
ati
onst
oimplementt
hecomponent
sofan
DATE: aut
omobil
e

Ai
m:
Towr i
teapr
ogr
am t
oimpl
ementt
hecomponent
sofanaut
omobi
l
eusi
ng
di
cti
onar
ies

Al
gor
it
hm:

St
ep1:
Starttheprogram
St
ep2:
Ini
tiali
zethedict
ionari
esfrom user
St
ep3:
Impl ementthedicti
onari
esoperati
onsuchasaddi
tems,accessingt
he
i
temsandcheckt heavail
abil
i
tystatususi
ngmembershi
poperator
St
ep4:
Printallout
puts.
St
ep5:
Stopt heprogram

Pr
ogram:
automobil
e1={ “
transmi ssion”:clutch,“body”:“
steer
ingsystem”,”
auxil
i
ary”
:”
seal
s”}
pri
nt(
“i
temsi nthedi ctionar ies:”,
aut omobil
es1)
automobil
e[“body2” ]=” wheel s”
pri
nt(
“addelementi nt hedi ctionaries:”,
aut
omobi l
e1)
pri
nt(
“accessingsingl eel ementi nt hedict
ionari
es:
”,aut
omobile1[
“body”
])
pri
nt(
“i
tem inthedi ctionar i
esornot :”
,”
body”inautomobile1)
pri
nt(
“i
tem inthedi ctionar i
esornot :”
,”
head”inautomobile1)

Out
put
:

i
tem inthedicti
onari
es:{
‘t
ransmission’
:’
cl
utch’,
’body ’:

steering
sy
stem’,’
auxi
li
ary’:

seats’
}
addelementi nthedicti
onari
es:{
‘t
ransmission’:
’clutch’,

body ’
:’
steeri
ngsy
stem’
,

auxil
ary’
:
’seats’
,’body 2’
”’wheels’}
accessi
ngsingleelementinthedictionar
ies:steeringsy stem
i
tem inthedicti
onari
esornot :
True
i
tem inthedicti
onari
esornot :
False

Result
:
Thust
hepythondi
cti
onar
iesoper
ati
onf
orcomponent
sofanaut
omobi
l
ewas
execut
edsuccessf
ully
.
EXPTNO:
Fact
ori
alusi
ngf
unct
ion
DATE:

Ai
m:
Towr
it
eaPy
thonpr
ogr
am f
orf
act
ori
alusi
nguserdef
inedf
unct
ions.

Al
gor
ithm:
Step1:
Starttheprogr am
Step2:
Ini
tial
izethev aluef ornum vari
abl
e
Step3:
Def i
netheuserdef inedfuncti
onfactori
al
Step4:
Checkt hev al
ueusi ngconditi
onalst
atement
Step5:
Calculatethef actorialbyusi
ngwhi l
eloop
Step6:
Printthefactorialresult
Step7:
Stopt heprogram

Program:
Deffactorial
(n):
i
fn<0:
return0
el
ifn==0orn==1:
return1
el
se
fact=1
whil
e(n>1) :
fact=fact
*n
n=n-1
returnfact

#Dri
vercode
num=int(
input(
“Ent
erthenumber”
))
pri
nt(
“Factor
ialof”
,num,
”is“,
fact
ori
al(
num)
)

Output:
Entert
henumber4
Factor
ialof4i
s24

Result
:
ThusthePy
thonpr
ogr
am f
orf
act
ori
alusi
nguserdef
inedf
unct
ionswasexecut
ed
successful
l
y.
EXPTNO:
Li
stf
unct
iont
ofi
ndLar
gestNumber
DATE:

Ai
m:
Towri
teaPy
thonpr
ogr
am t
ocal
cul
atet
hel
argestnumberi
nthel
i
stusi
ng
f
unct
ions.

Al
gor
it
hm:
St
ep1:Star
tthepr ogram
St
ep2:I
niti
ali
zethel i
stv al
ues
St
ep3:Callt
heappr opr i
ateuserdef
inedfunction(funct
ionname:lar
ge(
))
St
ep4:Describethefirstelementasmaxwi t
hinthedeff uncti
on.
St
ep5:Compar eeachel ementbyusi ngforloop.
St
ep6:Fi
ndt helargestelementbyusi ngifcondit
ions.
St
ep7:Thenr et
urnthel argestel
ementpresentint heini
tial
i
zedli
st
St
ep8:Stopthepr ogram.

Pr
ogr
am:

deflarge(arr)
:
#rootelementv ari
able
max=ar r[
0]
forelem inarr:
i
f(
elem>max) :
max=el
em
r
eturnmax
l
ist1=[1,
4,5,2,
6]
result
=large(l
ist
1)
print
(result
)

Output:
6
Result
:
Thust
hePythonpr
ogr
am f
orl
argestnumberi
nthel
i
stusi
ngf
unct
ionswas
execut
edsuccessf
ull
y.
.
EXPTNO:
Cal
cul
atet
hear
eaofdi
ff
erentshapesusi
ngf
unct
ions
DATE:

Ai
m:
Towri
teaPy
thonpr
ogr
am t
ocal
cul
atet
hear
eaofdi
ff
erentshapesusi
ng
f
unct
ions.

Algor
it
hm:
Step1:Starttheprogr
am.
Step2:Gett heshapefrom userforcalcul
ati
ngthearea
Step3:Calltheappropri
ateuserdefinedfuncti
on.
Step4:Calculatet
heareaofdi f
ferentshapesli
kerectangl
e,squar
e,t
ri
angl
e,ci
rcl
eand
paral
l
elogram.
Step5:Printtheareavalue
Step6:Stopt heprogr
am

Program:
defcal culat e_ar ea(name) :
name=name. l
ower ()
i
f (
name==" r
ect angl e"):
l=int(input ("enterr ectanglelengt h")
)
b=i nt(input ("enterr ectanglebreadt h"
))
r_ar ea=l *b
pr i
nt (
"ar eaofr ect angleis",
r_
ar ea)
eli
f(name==" squar e"):
s=i nt(input ("entersi deofsquar e")
)
s_ area=s* s
pr i
nt (
"ar eaofsquar ei
s",s_ar
ea)
eli
f(name==" triangl e"):
b=i nt(input ("enterr ectanglebreadt h"
))
h=i nt(input ("enterr ectanglehei ght"
))
t_ar ea=0. 5* b* h
pr i
nt (
"ar eaoft riangleis",t
_area)
eli
f(name==" ci rcl
e" )
:
r=int (
input ("ent err adi
usofci rcle")
)
c_ area=3. 14* r*r
pr i
nt (
"ar eaofsquar ei
s",c_ar
ea)
shape_ name=i nput ('enternameofshape' )
calculate_ area( shape_ name)

Output:
enternameofshape
ci
rcle
enterradi
usofci
rcl
e
5
areaofsquarei
s78.5

Resul
t:
ThusaPy
thonpr
ogr
am t
ocal
cul
atet
hear
eaofdi
ff
erentshapesusi
ngf
unct
ions
isexecut
edsuccessf
ull
y.
EXPTNO:
Py
thonpr
ogr
am t
oimpl
ementSt
ri
ngmet
hods
DATE:

Ai
m:
ToWriteapythonprogr
am f
orimpl
ementi
ngt
hestri
ngmethodsforr
ever
singt
he
st
ri
ng,count
ingthecharact
eri
nastri
ng,r
epl
aci
ngachar
acteri
nthest
ri
ngandcheck
whet
herthegivenst
ringispal
i
ndr
omeornot.

Algori
thm:
St
ep1:Starttheprogr am
St
ep2:Gett hestr
ingf rom t
heuserint hevariable(str)
.
St
ep3:Usingt hestri
ngmet hod[::
-1]
, f
ordisplayingther ever
seoft hestri
ng.
St
ep4:Usingt hefunct i
onispali
ndrome, checkwhet herthestr
ingi spali
ndr
omeor
not.
St
ep5:Usingt hestri
ngmet hodlen(str)
,f
orfindingthel engthofthegivenstr
ing.
St
ep6:Usingt hest r
ingmet hodreplace(),f
orr epl
acingachar acterinthestr
ing.
St
ep7:Stopt hepr ogram.

Program:
defisPal i
ndr ome(s):
returns==s[ ::
-1]
str=i nput("EntertheString:"
)
pri
nt("TheRev ereseoft hestri
ngi s",
st r
[::-
1] )
check_ pali
n=i sPal i
ndrome( str
)
i
fcheck_ palin:
pri
nt("TheGi venSt r
ingisapal indr ome" )
el
se:
pri
nt ("
TheGi venStri
ngi snotapal indr ome" )
pri
nt("Thel engthoft hegi vr
nstringis" ,
len( str
))
pri
nt("Replaceachar acterinthest r
ing",st r
.repl
ace(
'm'
,
'h'
,
2))

Output:
EntertheStri
ng:
madam
TheRev ereseofthestr
ingismadam
TheGi venStri
ngisapalindr
ome
Thelengthoft hegi
vrnstri
ngis5
Replaceachar act
eri
nthest r
inghadah

Result
:
Thusthepyt
honprogram f
orimplementi
ngt
hestri
ngmet hodsforrev
ersi
ngthest
ri
ng,
counti
ngthecharact
erinastri
ng,
replaci
ngachar
acteri
nthestringandcheckwhet
her
thegivenst
ri
ngispali
ndromeornotwasi mpl
ementedsuccessfull
y.
EXPTNO:
I
mpl
ement
ingSt
andar
dLi
brar
yfunct
ions
DATE:

Ai
m:
Toi
mpl
ementPy
thonpr
ogr
am usi
ngwr
it
tenmodul
esandPy
thonst
andar
d
l
i
brar
ies.

Al
gori
thm:
St
ep1:Starttheprogram
St
ep2:Ini
tial
i
zeanar r
ay.
St
ep3:Printtherangeofarr
aywi t
ht heuseofsl
i
cingmet
hod.
St
ep4:Printtheelementsatspeci
ficindi
ces.
St
ep5:Stopt hepr ogr
am.

Pr
ogr
am (
NumPy
)

i
mpor tnumpyasnp
#I nitial Ar
ray
ar
r=np. array (
[[
-1,2,
0,4]
,[
4,-0.5,6,
0],[
2.6,0,
7,8]
,[
3,-
7,4,
2.0]
])
pr
int("I
nitial Ar
ray:")
pr
int(arr)
#Pr intingar angeofAr ray
#wi tht heuseofsl icingmet hod
sl
iced_ arr=ar r[
:2,:
:2]
pr
int("Arraywi thf i
rst2rowsandal ternatecolumns(0and2) :
\n"
,sl
i
ced_
arr
)
#pr intingel ement sat
#speci ficIndices
i
ndex_ arr=ar r
[[
1,1,0,3]
,
[3,2,1,0]]
pr
int("\nElement sati ndices( 1,
3)(1,
2),(0,
1),(
3,0)
:\n"
,i
ndex_ar
r)

Output:
(NumPy)
I
niti
alArr
ay:
[
[-
1.2.0.4.]
[4.-0.56.0.]
[2.60.7.8.]
[3.-7.4.2.] ]
Arr
aywi t
hfi
rst2rowsandal
ter
nat
ecol
umns(
0and2)
:
[[
-1.0.]
[4.6.]]

El
ementsati
ndi
ces(
1,3)
(1,
2),
(0,
1),
(3,
0):
[
0.6.2.3.
]

Result
:
ThusaPythonprogr
am usi
ngwr
it
tenmodul
esandPy
thonst
andar
dli
brar
iesi
s
execut
edsuccessful
l
y.
EXPTNO:
Dr
awli
nesandbar
susi
ngMat
plot
li
b
DATE:
Aim:
Todr
awl
i
nesandbar
susi
ngMat
plot
li
b.

Al
gori
thm:
St
ep1:Startthepr ogram
St
ep2:ReadX- axi
sv alues.
St
ep3:ReadY- axi
sv alues.
St
ep4:Plotthel i
nesusi ngplot(
)funct
ion.
St
ep5:Plotthebarusi ngbar()f
uncti
on
St
ep6:Showt heli
nespl oted.
St
ep7:Stopt heprogr am

i
) Pr ogram forli
neplot
i
mpor t
mat plotl
i
b.pyplotaspl
t
x=[1,2,3,4, 5,6]
y=[1,5,3,5, 7,
8]
pl
t.
plot(
x,y)
pl
t.
show( )
Output(l
ineplot)
:

i
i) Pr ogram forBarplot
:
i
mpor tnumpyasnp
i
mpor tmat pl
otl
i
b.py
plotaspl
t
x=[5,
2,9,4,7]
y=[
10,5,8,4,2]
plt
.bar(x,
y )
plt
.show( )
Output(Barpl ot
)

Resul
t:
ThusaPy
thonpr
ogr
am i
sexecut
edusi
ngMat
plot
li
btodr
awl
i
nesandbar
s.
EXPTNO:
Fi
l
eoper
ati
ons
DATE:

Ai
m:
Towr i
teapyt
honprogram f
orimplementi
ngthef
il
ehandl
ingoperat
ionfor
perf
ormi
ngWor dcounti
nt hefi
l
e,longestwordint
hefi
leandcopythecontentofone
fi
lei
ntoanot
her.

Algor i
thm
Step1: Star tthePr ogr am
Step2: Creat eat extf ileast ext 1.t
xtandt ypecontentinit.
Step3: Opent hef il
ef 1( “text
1. txt”
)int her eadmode.
Step4: Creat et hef ilef 2(“text2. t
xt”)inthewr it
emode.
Step5: Readt hecont entf rom t hef i
le1andwr it
ei ntofil
e2
Step6: Closet het wof i
l
esf 1andf 2
Step7: Opent hef i
lef 3(“text
1. txt”
)int her eadmode.
Step8: Readt hecont ent sf r
om t hef il
ef 3usingt hemet hodr ead()
.spl
i
t()and
storedi tint hev ariables“ wor ds”
Step9: Printt hewor dcounti nt hef i
le.
Step10: Usi ngf orl oopandi fst atement ,pri
ntthel ongestwor di nthefil
e.
Step11: St opt hepr ogr am.
Creat eaf il
e
Text 1.txt
hello
thi
si smypy thonpr ogrammi ng
Progr am:
f1=open( “
text 1.txt’’
,”r”)
f2=open( ‘
e:\\ t
ext 2.txt”,
w’ )
str=f1.read( )
f2.wr i
te(str)
print(“
cont entoff il
e1( f1)i sr eadi twi l
lbewr it
et ofil
e2(f2)
”)
f1.close()
f2.close()
f3=open( t
ext 1.txt ”
,”r”
)
wor ds=f 3.
r ead( ).split
()
print(“
thewor dcounti nt hef il
e( f3)is”,
len(words))
max_ l
en=l en( max( wor ds,key=l en))
forwor dinwor ds:
iflen( wor d)==max_ l
en:
pr i
nt(“thel ongestwor di nt hefil
e(f
3)i
s”,word)
f3.close()
Out put:
cont entofFi le1(f1)i sreadandi twil
lbewr it
et oFil
e(f
2)
TheWor dcounti nt hef i
le(f
3)i s6
TheLongestWor di nthef il
e(f3)isprogrammi ng

Result
:
Thusthepythonprogram fori
mplement
ingthefi
lehandl
i
ngoper
ati
onfor
perf
ormingwor dcountinthefi
le,l
ongestwor
dt hefi
l
eandcopythecont
entofonef
il
e
i
ntoanot herwasi
mpl ementedsuccessful
l
y.
EXPTNO:
Except
ionHandl
i
ng
DATE:

Ai
m:
Towr i
teapy
thonpr
ogr
am t
oimpl
ementDi
vi
debyzer
oer
rorusi
ng
Except
ionhandl
i
ng.

Al
gor
it
hm:
St
ep1:Starttheprogram.
St
ep2:Gett hediv
idendanddivi
sorval
uesfrom theuser
.
St
ep3:Calculatet
hequot i
entv
alueusi
ngtryblock.
St
ep4:Checkt heDivi
debyZeroer r
ori
nCatchBl ock
St
ep5:PrinttheExcepti
onhandli
ngOutput
.
St
ep6:Stopt heProgram.

Program:
n=int
(input(
“Entertheval
ueofdi
vi
dend(n):
”))
d=int
(input(
“Entertheval
ueofdi
vidend(
d):
”))
c=int
(input(
“Entertheval
ueofdi
vi
dend(c):
”)
)
tr
y:
q=n/(d-c)
pri
nt(
“ Quoti
ent:
”,q)
exceptZeroDivi
sionErr
or:
pri
nt(
“ Div
isi
onbyZer o”)

Output:
Entertheval
ueofdi
vi
sor(
n):
6
Entertheval
ueofdi
vi
sor(
d):
3
Entertheval
ueofdi
vi
sor(
c):
3
Div
isionbyZero

Resul
t:
ThusthePythonprogr
am f
orDi
vi
debyz
eroer
rorusi
ngExcept
ionhandl
i
ngwas
i
mplementedsuccessf
ull
y.
EXPTNO:
Checkt
heVot
er’
sagev
ali
dit
y
DATE:

Ai
m:
Towr
it
eapy
thonpr
ogr
am t
ocheckt
hev
oter
’sagev
ali
dit
y.

Al
gori
thm:
St
ep1:St
arttheProgr am.
St
ep2:GettheVoter’
snameandagef rom theuser.
St
ep3:Cal
culatet
heel i
gibi
li
tyofvoter
’sageintr
yBlock.
St
ep4:ChecktheVal ueEr r
orinCatchBlock
St
ep5:Pri
nttheel
igibili
tyStatusofvoter
’sageusingExcept
ionhandl
i
ng.
St
ep6:St
opt heProgr am.

Program:
name=i nput (
“EntertheVot erName: ”
)
tr
y:
age=i nt(i
nput(“Enteryourage”))
i
fage>18:
pri
nt(“Eli
gibletov ote”
)
el
se:
pri
nt(“Notel i
gibletov ot
e”)
#displayexcept ion’sdefaul
terrormessage
except ValueErroraser r
:
pri
nt(err)
el
se:
#Codet obeexcut edwhent hereisnoexception
pri
nt(“Thanky ou, youhav esuccessfull
ycheckedthev
oti
ngel
i
gibi
l
ity
”)

Output1:
Entert
heVot erName: Kart
hick
Enteryourage:28
El
igibl
et ovote
Thanky ou,youhavesuccessful
l
ycheckedt
hev
oti
ngel
i
gibi
l
ity

Output2:
Ent
ertheVot erName: Ram
Ent
ery ourage:thir
y
I
nvali
dl i
ter
alforint
()wi
thbase10:

thi
ry’

Resul
t:
ThusthePyt
honprogram f
orvoter
’sagev
ali
dit
yusi
ngExcept
ionhandl
i
ngwas
i
mplementedandcheckedsuccessful
l
y
EXPTNO:
Expl
orePy
gamet
ool
DATE:

Ai
m:
Toexpl
oret
hepy
gamet
ool
stodr
awr
ect
angl
e.

Al
gori
thm:
St
ep1:StartthePr ogram.
St
ep2:Impor tpygamemodul e.
St
ep3:Setthedi splaymode.
St
ep4:Gett heev entname.
St
ep5:Drawt her ectangl
e.
St
ep5:Iftheev entnamei sQUI
T,l
eav
ethepy
game
St
ep6:Stopt hePr ogram

Program:
i
mpor tpy game
pygame. i
nt (
)
screen=py game. display.
set_mode((400,
300)
)
done=Fal es
whilenotdone:
forev entinpy game. event
.get(
):
i
fev ent.
type==py game. QUIT:
done=Tr ue
pygame. draw. r
ect(screen,
(0,
125,255),py
game.Rect
(30,
30,
60,
60)
)
pygame. display.
fl
ip()

out
put
:
Resul
t:
Thust
hepr
ogr
am i
simpl
ement
edusi
ngpy
gamet
ool
s.
EXPTNO:
Bounci
ngBal
l
DATE:
Aim:
ToDev
elopabounci
ngbal
lgameact
ivi
tyusi
ngpy
game.

Al
gor
it
hm:
Step1:
Startthepr ogram
Step2:
Downl oadt hebal l
imageandsav eiti
nthecor r
espondi
ngfolder
.
Step3:
Impor tnecessar ypygameModul e.
Step4:
Ini
ti
alizethev aluessuchasspeed, col
or,widt
handheight.
Step5:
Readandl oadt heimageusi ngpygamepr ocedure.
Step6:
Givet heBouncespeedwi thi
nt hewhileloop.
Step7:
Bouncet hebal lusingtheloopandcondi ti
onalstat
ements.
Step8:
Displaythebounci ngballoutputinscreen.
Step9:
Stopt heprogram.

Progr am:
Impor tos
os. env i
ron[ ‘
PYGAME_ HIDE_ SUPPORT_ PROMPT’ ]=“hide”
i
mpor tsy s,
py game
frompy game. l
ocal si mpor t*
py game. int()
speed=[ 1,
1]
col or=( 255, 250,250)
wi dth=550
hei ght=300
scr een=py game. displ ay.
set_mode( (widt
h, height))
py game. displ ay.set_ caption(“pygamebounci ngball”)
bal l=py game. i
mage. load(“
bal l
.
png”)
rect _boundr y=bal l.get _r
ect()
whi le1:
forev enti npy game. event.
get( )
:
rect _boundr y=r ect_ boundr y.
mov e(speed)
i
frect _boundr y.
left<0orr ect_boundry.ri
ght>wi dt
h:
speed[ 0]=- speed[ 0]
i
frect _boundr y.
top<0orr ect_boundry.bott
om>hei ght:
speed[ 1]=-speed[ 1]
scr een. fi
ll(
col or)
scr een. blit
(bal l
,
rect _boundr y )
py game. displ ay.fl
ip()
i
fev ent .type==QUI T:
py game. qui t()
sy s.exit()

Out
put
:
Resul
t:
Thust
hebounci
ngbal
lgameact
ivi
tyusi
ngpy
gamewassuccessf
ull
y
execut
ed.

EXPTNO:
CarRace
DATE:

Ai
m:
Todev
elopagameact
ivi
tyusi
ngpy
game.

Al
gor
it
hm:
Step1:Startthepr ogram
Step2:Downl oadt heimagesuchasenemycarandsav eitinthecorrespondi
ng
fol
der.
Step3:I
mpor tnecessar ypygamemodul e.
Step4:I
niti
alizethev aluessuchasspeed, cl
ockti
me,racepathandwi dt h.
Step5:Readandl oadt heimageusingpy gamepr ocedure.
Step6:Declaredeff unctionforal
ltheactivi
ty.
Step7:StarttheCarRaci ngwit
hthehelpofl oopandcondi t
ionalst
atement s,
Step8:DisplaytheCr editScoreoutputi
nscr een.
Step9:Stopt heprogram.

Pr
ogr
am:

i
mpor trandom
fr
om timei mpor tsl
eep
i
mpor tpygame
cl
asscar raci
ng:
def_i
nit
_(self)
:
pygame. i
nit(
)
sel
f.di
splay_wi dth=800
sel
f.di
splay_hei ght=600
sel
f.bl
ack=( 0,0,0)
self.
whi te=( 255, 255, 255)
self.
clock=py game. time. clock( )
self.
gamedi spl ay=none
self.
initi
al i
ze( )
definitialize( sel f
) :
sel f
.crashed=f alse
self.
car lmg=py game. i
mage. l
oad( ‘
.\\i
mg\ \car.png’ )
self.
car _x_ coor dinat e=( self .
displ ay_width* 0.45)
self.
car _y _coor dinat e=( self .
displ ay_height* 0.8)
self.
car _wi dt h=49
#enemy _car
self.
enemy _ car=py game. image. l
oad( ‘
.\
\img\ \enemt _car1.png’)
self.
enemy _ car _st ar t
x=r andom. randrange( 310, 450)
self.
enemy _ car _st ar t
y=- 600
self.
enemy _ car _speed=5
self.
enemy _ car _wi dt h=49
self.
enemy _ car _hei ght =100
#backgr ound
self.
bgl mg=py game. image. load( “
.\\i
mg\ \ back_ gr ound. j
pg”)
self.
bg_ x1=( self.di splay _ widt h/2)–( 360/ 2)
self.
bg_ x2=( sel f.
di spl ay _wi dt h/2)-(360/2)
self.
bg_ y 1=0
self.
bg_ y 2=- 600
self.
speed=3
self.
count =0
defcar (
sel f,car _x_ coor di nat e,car _y_coor dinate) :
self.
gamedi splay .
bl it
(sel f.car l
mg, (car_x_ coordi nate, car_y
_ coordi
nat
e) )
defr aci ng_ wi ndow( sel f):
self.
gamedi splay =py game. displ ay.
set_model ((self.
display_width,
sel
f.di
splay_hei
ght
))
pygame. di spl ay .
set _capt ion( ‘cargame’ )
self.run_car ()
defr un_ car ( self):
whi l
enotsel f.crashed:
forev enti npy game. ev ent .get ():
ifev ent. ty pe==py game. qui t:
self.cr ashed=t rue
py game. qui t()
qui t
()
#pr i
nt (ev ent )
i
f(ev ent .type==py game. key down) :
i
f( ev ent .key==py game. .k_left)
:
sel f.
car _x_ coor dinat e-=50
pr i
nt (“carxcoor dinat es: %s” %sel f
.car _x_coor dinate)
if(ev ent .key==py game. k_right):
sel f.car _x_ coor dinat e+=50
pr int(“carxcoor dinat es: %s” %sel f.
car _x_ coor dinate)
print(“x:{x} ,y:
{y }”.format (x=sel f .
car_x-coor dinat e,y
=sel f
.car_y_coor
dinate))
self.
gamedi spl ay .fill
(sel f.black)
self.
back_ gr ound_ road( )
self.run_ enemy _car (sel f.enemy _car_startx ,
self.enemy _car_start
y)
self.
enemy _ car _st ar t
y +=sel f .
enemy _car_speed
i
fsel f.enemy _car _ star t y>sel f.display _ height :
self.enemy _car _ st ar ty=0–sel f.
enemy _car _hei ght
self.enemy _car _ st ar tx=r andom. randr ange( 310, 450)
sel f.
car (sel f.car _x_ coor di nat e,self.car _y_coor dinat e)
sel f.
highscor e(sel f .
count )
sel f.
count +=1
i
f( self.count %100==0) :
self.enemy _car _ speed+=1
self.bg_ speed+=1
i
fsel f.car _y _coor di nat e<sel f
.enemy _car _star ty+sel f.
enemy _car_height:
i
f( self.car _x_ coor di nat e>sel f.enemy _ car_st artxand
sel f.
car _ x_coor dinat e<sel f.enemy _ car _startx +
sel f.
enemy _ car _wi dt horsel f.car_x_ coor dinat e+sel f.
car_wi
dt h>self
.enemy _car
_st
art
x
andsel f.car _ x_coor dinat e+sel f.
car _wi dth<sel f .
enemy _car_start
x+self.
enemy _car
_wi
dth)
:
self.cr ashed=t rue
self.displ ay _ message( “gameov er! !!
”)
i
f.sel f.car _x_ coor di nat e<310orsel f.
car _x_ coor dinat e>460:
self.cr ashed=t rue
self.displ ay _ message( “gameov er! !!
”)
py game. di spl ay .
updat e()
sel f.
cl ock. t i
ck( 60)
defdi spl ay _message( sel f,msg) :
f ont =py game. font .sy sf ont (“comi csansms” ,72, true)
text =f ont .
render (msg, true, (255, 255, 255) )
sel f
.gamedi spl ay .blit(t ext ,
(400- t
ex t.get_wi dt h() 2,240_ t
ext.
get _hei
ght (
)2))
sel f
.displ ay _ credi t( )
py game. displ ay .updat e( )
sel f
.clock. tick( 60)
sl eep( 1)
car _raci ng. initialize( )
car _raci ng. raci ng_ wi ndow( )
defback_ gr ound_ road( sel f):
self.gamedi spl ay .bl it(sel f.
bgl mg, (sel f.
bg_ x1,sel f.bg_y1))
self.gamedi spl ay .bl it(sel f.
bgl mg, (sel f.
bg_ x2,sel f.bg_y2))
self.bg_ y1+=sel f .
bg_ speed
self.bg_ y2+=sel f .
bg_ speed. gamedi splay .blit(
ifsel f.bg_ y1>=sel f.di spl ay _height :self.
bg_ y1=- 600
ifsel f.
bg_ y 2>=sel f .
di spl ay _ height :
sel f.
bg_ y2—600
defr un_ enemy _car (sel f,thingx ,thingy ):
sel f.
gamedi spl ay .bl i
t( sel f.
enemy _
car ,
(thingx ,
thingy ))
defhi ghscor e( sel f,
count ):
font =py game. f ont .sy sf ont (
“ar i
al”,20)
text =font .r
ender (“scor e:”+st r(count ),
true,sel f.whi te)
sel f.
gamedi spl ay .bl i
t( text .(0,0)
defdi spl ay _cr edi t(sel f ):
font =py game. font .sy sf ont (“lucidaconsol e”,14)
tect =font .r
ender (“thanksf orpl ay i
ng–madhu, ramy a!”,
true,
self.
white)
sel f.
gamedi spl ay .bl i
t( text ,
( 500, 420) )
i
f_ _name_ _’==_ _ mai n_ _ ’:
car_ raci ng=car raci ng( )
car
_raci
ngr
aci
ng_
window(
)

Out
put
:

Resul
t:
Thust
hecarr
acegameact
ivi
tyusi
ngpy
gamewassuccessf
ull
yexecut
ed.

You might also like