You are on page 1of 119

PROBLEM SOLVI

NG USI
NG PYTHON

QUESTI
ON BANK

UNI
TI

ALGORI
THMI
CPROBLEM SOLVI
NG

PART- A (
2 Ma
rks
)

1
. Wh
ati
sana
lgo
rit
hm?

Al
gori
thmi
sa norder
eds equ
enc
eoffi
nit
e,welldefi
ned,un
ambi
guo
us
in
stru
ctio
nsforco
mplet
ingat a
sk .I
tisanEn
gli
sh-l
ikerep
resen
tat
ionofthel
ogi
c
whic
hi susedtosol
ve

t
hep r
obl
em.I
ti sast
ep-by-st
eppro
cedur
efors
olv
ingat
asko
rap
rob
lem.Th
e
s
tep
smu s
tbeo r
der
ed,un
amb
igu
ousa
ndf i
nit
einnu
mber.

2.Wri
tea nal
gori
thmtof
indmi
nimu
mof3number
sina
li
st.ALGORITHM :Fi
ndMin
imumof3n
umbersina
li
st
St
ep1
:St
art

Step2:Rea
dthethr
eenumb
ers
A,B,CStep3:Co
mpareA a
ndB.

IfA i
smi
nimu
m,g ot
ostep4 el
seg
oto
s
tep5.St
ep4:Compar
eA andC.

IfA i
smi
nimu
m,ou
tpu
t“Aismi
nimu
m”el
seo
utp
ut“
Cismi
nimu
m”.Got
o
s
tep6.St
ep5:Compa
reB a
ndC.

I
fB i
smi
nimu
m,o
utp
ut“
Bismi
nimu
m”el
seo
utp
ut“
Cismi
nimu
m”.

St
ep6:St
op
3.Li
stt
hebu
ildi
ngbl
ockso
fana
lgo
rit
hm.

Th
ebu
ildi
ngb
loc
kso
fana
lgo
rit
hma
re

 St
atemen
ts

 Seq
uen
ce

 Sel
ect
iono
rCo
ndi
tio
nal

 Rep
eti
tio
norCo
ntr
olf
low

 Fu
nct
ion
s

4.
Def
ines
tat
emen
t.Li
sti
tst
ypes
.

Stat
ementsareinst
ruct
ion
sinPytho
ndesi
gneda sco
mpo
nen
tsf o
ra l
gor
ith
mic
p
robl
em so
lvi
ng,rat
hert h
ana so
ne-t
o-onet
ransl
ati
onsoft
heu n
derlyi
ngmachi
ne
l
ang
uageinst
ruc
tionsetoft hec
ompu
ter.

Therea r
et hreetypesofhi
gh-levelpro
gra
mminglang
uages t
atement
s
I
nput/
outpu
ts ta
tementsmakeuponetyp eofstat
ement
.Ani np
uts ta
tementco
llects
aspeci
ficvalu
ef r
omtheu s
erforav ari
abl
ewithinth
ep ro
gram.Ano utpu
t
s
tat
ementwr i
tesames sag
eo rt
heva l
u eofap r
ogramvar
iabl
et ot heuser
sscreen
.

5.Writ
et hep
seu
doc
odet
oca
lcu
lat
eth
esu
man
dpr
odu
cto
ftwon
umber
san
d
dis
pla
yi t
.

I
NITI
ALI
ZE v
ari
abl
ess
um,p
rodu
ct,n
umb
er1
,nu
mber
2oft
yper
eal
PRI
NT “
Inp
utt
won
umb
ers

READ n
umber
1,n
umber
2
su
m= n u
mber
1+ nu
mber2

PRI
NT “
Thes
umi
s“,s
um

COMPUTE p
rodu
ct= n
umb
er1*n
umb
er2

PRI
NT “
ThePr
odu
cti
s“,p
rodu
ct

END p
rog
ram
6.Ho
wdo
esf
lowo
fco
ntr
olwo
rk?

Cont
rolflow( o
rf lo
wo fcon
trol
)istheorderinwh ichindi
viduals
tat
ements
,
ins
truct
ionsorfunct
ioncal
lsofa ni
mper
ati
vep ro
g r
ama reexec u
tedorevalu
ated.A
cont
rolf l
ows t
atementisastat
ementi
nwhichex ecut
ionresu
ltsi nachoi
ceb ei
ng
madea stowh ichoft woormor
ep a
thstofoll
ow.

7.Wh
ati
saf
unc
tio
n?

Funct
ion
sa re"s
elf-con
tained"modul
esofc odet hata
cco
mplis
has p
ecif
ictask.
Functi
onsusua
lly"tak
ei n"dat a
,proc
essit
,a n
d" retur
n"aresu
lt.On
ceaf unct
ionis
wri
tten,itcanb eus
edo vera ndoverandovera g
a i
n.Fun
cti
onscanbe"ca
lled"fro
m
th
ei nsi
deo fo t
herfunc
tions
.

8.Wr
itethepseu
doco
det
oca
lcu
lat
eth
esu
man
dpr
odu
ctdi
spl
ayi
ngt
hea
nswero
n
th
emonit
orsc
reen.
I
NITI
ALI
ZE v
ari
abl
ess
um,p
rodu
ct,n
umb
er1
,nu
mber
2oft
yper
eal

PRI
NT “
Inp
utt
won
umb
ers

READ n
umber
1,n
umber
2
su
m= n u
mber
1+ nu
mber2

PRI
NT “
Thes
umi
s“,s
um

COMPUTE p
rodu
ct= n
umb
er1*n
umb
er2

PRI
NT “
ThePr
odu
cti
s“,p
rodu
ct

END p
rog
ram

9.
Giv
eth
eru
lesf
orwr
iti
ngPs
eudoc
odes
.

·Writ
eones t
atemen
tp er
li
ne.·Capi
tal
izeini
tia
l
keywo
rds
.·I n
denttos ho
w
h
ierar
chy.·En
dmu
lti
lin
e
s
tru
cture.

·Keeps
tat
emen
tst
obel
ang
uag
ein
dep
enden
t.

1
0.Gi
vet
hedi
ffer
enc
ebet
weenf
lowc
har
tan
dps
eudoc
ode.

Fl
owchartandPseudocodea r
eu sedt odoc
umentandrepres
entt h
ea lgo
r i
thm.In
ot
herwo r
ds,a na
lgori
thmcanber epres
entedusi
ngaf lo
wchar
to rap seudoc ode.
Flowc
hartisag rap
hicalr
epres
entat
iono fthealgo
rit
hm.Pseu
doc odei sar eadabl
e,
fo
rmallystyledEngli
shli
kel a
nguagerepres
enta
tio
no fthealgor
ithm.

1
1.Def
ineaf
lowc
har
t.

Aflowcha
rti sadiagra
mma ti
crepr
esenta
tio
no ft
helo
gicf
orsol
vingatask
.A
f
lowchar
ti sdrawnusi
ngb ox
eso fdif
ferentshapeswit
hli
nesc
onn
ecti
ngthemtoshow
t
hef lo
wo fc on
trol
.Thep urpo
seo fdrawi
ngaf l o
wcha
rti
stomakethelogi
co ft
he
p
rogra
mc lear
eri nav i
sua
lf orm.

1
2.Giveanexamp
leof
i
tera
tio
n.a= 0

f
orif
rom1t
o3 //l
oopt
hreet
imes

a= a+ i /
/addt
hec
urr
entv
alu
eofit
oa

p
rin
ta /
/th
enu
mber6i
spr
int
ed(
0+1
;1+ 2;3+ 3)

1
3.Wr
itedo
wnt
her
ulesf
orp
rep
ari
ngaf
lowc
har
t.

Wh
iledr
awi
ngaf
lowc
har
t,s
omer
ulesn
eedt
obef
oll
owed—

(
1)A f
lowc
har
tsh
oul
dha
veas
tar
tan
den
d,

(
2) Th edi
rec
tio
noff
lowi
naf
lowc
har
tmu
stb
efr
omt
opt
obo
tto
man
dlef
tto
r
igh
t,and
(
3)Th
erel
eva
nts
ymb
olsmu
stb
eus
edwh
iledr
awi
ngaf
lowc
har
t.

1
4.Li
stt
hec
ateg
ori
eso
fPr
ogr
ammi
ngl
ang
uag
es.

Pr
ogr
ammi
ngl
ang
uag
esa
redi
videdi
ntot
hef
oll
owi
ngc
ateg
ori
es:

In
terpr
eted,Fun
cti
ona
l,Compi
led,Proc
edur
al,Sc
ript
ing
,Ma
rku
p,Lo
gic
-Ba
sed,
Conc
urr
enta n
dOb j
ect-Or
ien
tedPr o
grammi
ngLangu
ages

1
5.Men
tio
nth
ech
ara
cter
ist
icso
fana
lgo
rit
hm.

 Al
gor
ith
msh
oul
dbep
rec
isea
ndu
namb
igu
ous
.

 I
nst
ruc
tio
nina
nal
gor
ith
msh
oul
dno
tber
epea
tedi
nfi
nit
ely.

 En
sur
eth
att
hea
lgo
rit
hm wi
llu
lti
mat
elyt
ermi
nat
e.

 Al
gor
ith
msh
oul
dbewr
itt
eni
nseq
uen
ce.

 Al
gor
ith
msh
oul
dbewr
itt
eni
nno
rma
lEn
gli
sh.

 Des
iredr
esu
lts
hou
ldb
eob
tai
nedo
nlya
ftert
hea
lgo
rit
hmt
ermi
nat
es.

1
6.Co
mpa
rema
chi
nel
ang
uag
e,a
ssembl
yla
ngu
agea
ndh
igh
-lev
ell
ang
uag
e.

Mach
ine lan
gua
ge isa c
oll
ect
ion o
f b
ina
ry di
git
sorb
itst
hatt
he
co
mputer r
eads a
nd
i
nter
pret
s.Th
isl
ang
uag
eisn
otea
sil
yun
der
sta
nda
bleb
yth
ehu
man
.

Anassemb l
yl angu
agedi rectl
yc ontr
olsthep h
ysica
lh ardwar
e.A p ro
gram wri
ttenin
ass
emblyl a
ng uag
ec onsi
stsofas er
ieso fins
tru
ction
smn emoni
cst h
atc or
resp
ondt oa
st
reamofex ecuta
blei n
stru
ctions
,wh entran
slat
edb ya na s
semblerc a
nb eloadedi n
to
memoryandex ecut
ed.Th ep ro
g r
amswr i
tteninthislanguag
ea ren otport
ableandt he
debug
gingp r
o ces
si salsonotv eryea s
y.

Ahi
ghl ev
ellan
gu a
geismuchmo
rea bst
rac
t,t
hatmus
tb etra
nslat
edo rcompi
led
i
ntomach
inelan
guage.Iti
sea
sil
yunder
sta
ndab
leandt
hepro
gra
msa r
ep or
tab
le.Deb
ugg
ing
t
hec
odei
sea
sya
ndt
hep
rog
ramwr
itt
eni
sno
tma
chi
nedep
enden
t.
1
7.Wh
ati
sth
edi
ffer
enc
ebet
weena
lgo
rit
hma
ndp
seu
doc
ode?

Ana lgo
rit
h misas ys
temati
cl og
icalappr
oachus
edt oso
lvepro
blemsina
c
omputerwhil
ep s
eudocodeist h
es ta
tementinpla
inEngl
ishth
atma ybe
t
ran
slatedlatertoap rogr
amminglangua
ge.Pseu
doc o
deistheint
ermedi
ary
b
etweena l
gorit
hma ndprogr
am.

1
8.Li
sto
utt
hes
imp
les
tep
stodev
elo
pana
lgo
rit
hm.

Al
gor
ith
m devel
opmen
tp r
oces
scons
ist
soffi
vema
jor
st
eps.Step1
:Ob t
ainadescr
ipt
ionoft
he
pr
oblem.

St
ep2:An
alyz
eth
epr
obl
em.

St
ep3:Dev
elo
pah
igh
-lev
ela
lgo
rit
hm.

Step4:Refi
nethealg
orith
mb yaddingmo
re
deta
il.St
ep5:Revi
ewt h
ea lg
ori
thm.

1
9.Gi
vet
hedi
ffer
enc
esbet
weenr
ecu
rsi
ona
ndi
ter
ati
on.

Rec
urs
ion I
ter
ati
on

Func
tio
ncall
sit
sel
fun
tilt
heb
ase Repeti
tio
nofp
roc
essu
nti
lth
eco
ndi
tio
n
co
nditi
oni
s fai
ls.
r
eac
hed.

Onlybas
econdi
tio
n(t
ermi
nat
ing I
ti n
volv
esf
ours
tep
s:i
nit
ial
iza
tio
n,
co
ndit
ion
)is c
ondit
ion
,
s
pec
ifi
ed. ex
ecu
tio
nan
dup
dat
ion
.

I
tkeep
sou
rco
des
hor
tan
dsi
mpl
e. I
ter
ati
vea
ppr
oac
hma
keso
urc
odel
ong
er.
I
tisslo
werth
ani
ter
ati
ondu
eto
o
ver
hea
do f I
ter
ati
oni
sfa
ster
.
ma
int
ain
ings
tac
k.

Ittakes mo
re memo
ry t
han i
ter
ati
on
due t
o I
ter
ati
ont
akesl
essmemo
ry.
o
ver
hea
dofma
int
ain
ings
tac
k.
20.Wh
ata
rea
dva
nta
gesa
nddi
sadv
ant
ageso
frec
urs
ion
?

Adv
ant
ages Di
sadv
ant
ages
Recu
rsi
vef
unc
tio
nsma
ket
hec
odel
ook Somet
imest
hel
ogi
cbeh
indr
ecu
rsi
oni
s
cl
ean ha
rdt o
a
ndel
ega
nt. f
oll
owt
hro
ugh
.

A co
mplex t
ask c
an b
e b
rok
en Recu
rsi
ve cal
lsar
e ex
pen
siv
e
do
wn in
to (i
neff
ici
ent
) as
s
imp
lers
ub-p
rob
lemsu
sin
grec
urs
ion
. t
heyt
akeu
pal
oto
fmemo
rya
ndt
ime.

Sequen
ce g
ener
ati
on i
s ea
sier wi
th
rec
ursi
on Rec
urs
ivef
unc
tio
nsa
reh
ardt
odeb
ug.
t
hanu
sin
gso
men
est
edi
ter
ati
on.

PART B (
16MARKS)

1
.Wh
ata
ret
heb
uil
din
gbl
ock
sofa
nal
gor
ith
m?Ex
pla
ini
ndet
ail
.

Th
eb ui
ldi
ngb l
ock
so fa
lgo
rit
hm
a
re-St a
tement
s

-Stat
e-
Con
trolflo
w
-Func
tio
ns

St
atemen
ts:
Th
erea r
e3t ypesof
st
atements
:-
Inp
ut/OutputSta
t emen
t
-Assi
gnmentStatement-
Cont
rolSt a
temen
t

St
ate:

Th
ereare3typesof
s
tat
e:-I
niti
al
s
tat
e-Curr
ent
s
tat
e

-Fi
nals
tat
e

Co
ntro
lf l
ow:
-Sequ
ence

Th
eseq
uen
ces
tru
ctu
rei
sth
eco
nst
ruc
twh
ereo
nes
tat
emen
tisex
ecu
teda
ftera
not
her

-Sel
ect
ion

Thesel
ect
ions
truc
turei
sthec o
nstr
uctwh
erestat
emen
tscanex
ecut
edorski
ppeddepen
din
g
onwh
etheracondi
tio
neval
uat
est oTRUE orFALSE.Ther
eareth
rees
elec
tionst
ruc
tur
esin
C:

1
.IF

2.
IF — ELSE

3.
SWI
TCH

-Rep
eti
tio
n

Therep
eti
tio
ns t
ruc
tureisthec
ons
tru
ctwher
esta
t emen
tscanb
eex ecut
edrepea
t edl
y
un
tilacon
diti
onevalu
atest
oTRUE orFALSE.Therea r
etworep
etit
ionst
ruc
turesinC:

1
.WHI
LE

2.
FOR

Fu
nct
ion
s:

Af
unc
tio
nisab
loc
kofo
rga
niz
edr
eus
abl
eco
det
hati
sus
edt
oper
for
m as
ing
lea
cti
on.
2.Br
ief
lydes
cri
bei
ter
ati
ona
ndr
ecu
rsi
on.I
llu
str
atewi
tha
nex
amp
le.

I
TERATI
ON:

S.
no. I
ter
ati
on Rec
urs
ion

The p
roces
sisr
epea
ted The func
tio
n c
all
sit
sel
f u
nti
lth
e b
ase
1 un
tilthe co
ndi
tio
n i s

c
ondi
tio
nfa
ils
. s
ati
sfi
ed.

2 I
tco
nsu
mesl
essmemo
ry. I
tco
nsu
mesmo
rememo
ry

3 I
tisf
ast
er I
tiss
lower

4 Th
eco
dei
slo
ng. Th
eco
dei
ssh
ort
.

Trac
ing i
s ea
sier i
f a
ny
5 pr
oblem Tr
aci
ngi
sdi
ffi
cul
tifa
nyp
rob
lemo
ccu
rs.

o
ccu
rs.

Ex
ampl
e:I
ter
ati
vea
lgo
rit
hmf
orf
act
ori
alo
fan
umber

St
ep1
:St
art
St
ep2:Rea
dnu
mbern

St
ep3:Ca
llf
act
ori
al(
n)

St
ep4:Pr
intf
act
ori
alf

St
ep5:St
op

f
act
ori
al(
n)

St
ep1
:In
iti
ali
zef
=1,
i=1

St
ep2:Repeats
tep2.1a
nd2.
2un
tili
<=nSt
ep
2.1
:f=f*i

Step2.
2:I
ncr
emen
tib
y1(
i=i
+1)St
ep
3:Ret
urnf

Ex
amp
le:Rec
urs
ivea
lgo
rit
hmf
orf
act
ori
alo
fnu
mber

St
ep1
:St
art

St
ep2:Rea
dnu
mbern

St
ep3:Ca
llf
act
ori
al(
n)

St
ep4:Pr
intf
act
ori
alf

St
ep5:St
op

f
act
ori
al(
n)

St
ep1
:Ifn
==1t
henr
etu
rn1

St
ep2:El
sef
=n*
fac
tor
ial
(n-1
)

St
ep3:Ret
urnf
3.Ex
pla
ini
ndet
ailAl
gor
ith
micp
rob
lems
olv
ing
.
4.Wr
itea
nal
gor
ith
man
ddr
awaf
lowc
har
ttoc
alc
ula
te
4
2.

Al
gor
ith
m:

St
ep1
:St
art

St
ep2:I
nit
ial
izet
hev
alu
eofr
esu
lt,r
=1.

St
ep3:Rep
eats
tep
4fo
r4 t
imes

St
ep4:c
alc
ula
ter
=r*
2

St
ep5:Pr
intt
hev
alu
eofr

St
ep6:St
op

Fl
owc
har
t:
5.a
) Des
cri
bep
seu
doc
odewi
thi
tsg
uidel
ines
.

Pseu
doc odec on
sis
tso fs
hor
t,r
eada
bleandfor
mal
ly-st
yledEngl
ishl
ang
uageusedf
or
expl
ain
ingana lg
o r
ith
m.Ps eu
docodedoesnoti
ncl
udedet
ail
sl i
kevar
iab
ledecl
ara
tio
ns,
su
brout
inesetc
.

Pr
epa
rin
gaPs
eudoCo
de

 Ps
eudoc
odei
swr
itt
enu
sin
gst
ruc
tur
edEn
gli
sh.

 I
nap seu
docode,somet
ermsa
rec
ommo
nlyu
sedt
orep
res
entt
hev
ari
ous
a
cti
ons
.Forex
a mpl
e,

fo
ri n
put
tingdatatheter
msmaybe(INPUT,GET,
READ),forout
putt
ingdat
a(OUTPUT,PRINT,
DISPLAY),

f
orc
alcul
ati
ons(
COMPUTE,CALCULATE)
,
f
ori
ncr
ementi
ng(INCREMENT)
,

i
naddi
tiontowordslik
eADD,SUBTRACT,I
NITI
ALI
ZE u
sedf
ora
ddi
tio
n,s
ubt
rac
tio
n,
a
ndini
tia
liz
ati
on,res
pecti
vel
y.

 Thecon
trolstr
uct
ures
—seq
uen
ce,s
elec
tio
n,a
ndi
ter
ati
ona
rea
lsou
sedwh
ilewr
iti
ngt
he
ps
eudocode.

 Th
eseq
uen
ces
tru
ctu
rei
ssi
mpl
yas
equ
enc
eofs
tep
stob
eex
ecu
tedi
nli
nea
ror
der
.

Th esel
ec ti
onc ons
tructs
—ifs t
atemen
ta ndc as
es tat
ement.Int heif-st
atement,ifthe
condi
tio
ni st r
uet hent heTHEN p ar
ti sex ecut
edo therwis
et heELSE p ar
ti sexecut
ed.
Therec anb ev ar
iati
onso ftheif-st
atementa lso,li
ket herema ynotb eanyELSE p artor
theremayb en es
tedi fs.Thec a
sestatemen tisusedwh eret h
erear ean umberof
condi
tio
nst ob ec hecked.Inac asestatement,dependingo nthevalueo ftheex pr
ess
ion
,
oneo fthec onditi
onsist ru
e,forwhicht hec orr
espondi
ngs ta
tement
sa reex ecu
ted.Ifno
matchfort heex pres
sionoccur
s,thentheOTHERS o pti
onwh ichisalsothedef aul
toptio
n,
isexecuted.

 WHI
LE a
ndFOR a
ret
het
woi
ter
ati
ves
tat
emen
ts.
b
)Gi
vea
nex
amp
lef
orp
seu
doc
ode.

Ps
eudo
codef
orf
indi
ngma
ximu
minal
ist
:

BEGI
N

SET
nu
mli
st=[]
GET n

FOR i
=1t
on

GET n
uml
ist
el
emen
tsENDFOR

SET max
imu
m=
nu
mli
st[
0]FOR ii
n
nu
mli
st

I
F(n>maxi
mum)
ma
ximu
m= n

ENDIF
ENDFOR
PRINT ma
ximu
m
END

c
)Wr
itet
hep
seu
doc
odef
orTo
wer
sofHa
noi
.

Ps
eudo
code

START
Pr
ocedu
reHa
noi
(di
sk,s
our
ce,des
t,a
ux)
I
F di
sk= = 0,THEN

mo
vedi
skf
roms
our
cet
odes
t

ELSE

Hanoi
(dis
k- 1,s
our
ce,aux,
dest
)mo vedi
skfro
ms o
urceto
destHanoi
(di
sk- 1
,aux,dest
,
so
urce)
END I
F

END Pr
ocedu
re

6.a
)Wh
ati
sfl
owc
har
t?

Fl
owch
artisadi agr
amma t
icrepr
esent
ati
onofthel
ogi
cforsolvi
ngat as
k.A
f
lowch
artisdrawnusi
ngb ox
eso fdiff
erentsha
peswit
hli
nesco
nnec
tingthemtoshow
t
hef l
owo fcon
trol
.Thep urpo
seo fdrawi
ngaf lo
wch
arti
stomaket h
el o
g i
cofthe
p
rogr
amc l
ear
eri nav i
sua
lf orm.

b
) Li
stdo
wns
ymb
olsa
ndr
ulesf
orwr
iti
ngf
lowc
har
t.
c
) Dr
awaf
lowc
har
ttoc
oun
tan
dpr
intf
rom1t
o10.
7.a)Writ
ea na
lgo
rit
hma
ndg
ivet
hef
lowc
har
ttof
indt
hen
ets
ala
ryo
f
anemp
loyee.
Al
gor
ith
m:

St
ep1
:St
art

St
ep2 :Rea
dth
eba
sics
ala
ry

St
ep3:I Ftheb a
sicisgr
eatert
hano
requalt
o4000
ELSE GotoStep4 Step3.
1:DA= 0.
32 *b
asi
c
(Dea
rnes
sAl l
owan
ce)

Step3,2 :HRA = 0.
15*basi
c(Hous
eRent
Allowa
nce)Step3.
3:CCA = 325( Cit
y
Compens
ato
ryAllo
wa n
ce)St
ep3.4 :NetSal
ary
ba
s i
c+ DA HRA + CCA

St
ep4 :Pri
ntt
heNet
Sa
lar
yStep5:Sto
p
b
)Wr i
tea
nal
gor
ith
man
dgi
vet
hep
seu
doc
odet
ogu
essa
nin
teg
ern
umb
eri
na
r
ang
e.

Al
gor
ith
m:

s
tep1
:Star
tth
ep r
ogram
s
tep2:Rea
dan'n
'n u
mber

s
tep3:Rea
danGu
essn
umb
er

st
ep4:ifGues
s>n ;p
rin
t" Yo
urGues
stoohi
gh"Step5:el
ifGu
ess<n;p
rin
t"Yo
ur
Gues
sto
olow"step6:eli
fGu es
s= = n
;pr
int"Go
o djo
b"

Step7:el sepri
nt"
Nop
e
"St ep:8 Sto
pt he
pr
o g
r a
m

Ps
eudo
code:

BEGIN
READ n

READ Gu
ess=
20 I
F Gues
s>n

pr
int
"YourGuessto
oHigh"el
ifGu
ess
<n
pr
int"YourGuessto
olo
w"elifGu
ess= =
20 pr
int"Goo
dJo b"

ELSE
pr
int
"No
pe"

8.a
)Wr
itea
nal
gor
ith
mtoi
nser
tac
ardi
nal
isto
fso
rtedc
ards
.

ALGORITHM:
Step1
:Start

Step2:Dec
lar
eth
eva
ria
blesN,Li
st[
],
I
an
dX
Step3:READ Nu
mberofel
emen
tins
ort
ed
li
stasN Step4:SET i
=0

Step5:I Fi
<N THEN g
otostep6ELSE go
tostep9Step6:READ So
rtedli
stel
emen
t
asList
[i]

St
ep7:i
=i+1

St
ep8:g
otos
tep5

Step9:READ El
ementt
ob e
in
serta
sX Step10:SET i
=N-1

Step11
:IFi>0 AND X<Li
st[
i]THEN g
otos
tep1
2 ELSE g
o
tostep15St
ep13:i=i-1

Step1 4:gotost
ep
1
1St ep1 5:
Li
s t
[i+1]
=X St
ep
1
6:St op

b
)Wr
itea
nal
gor
ith
mtof
indt
hemi
nimu
mnu
mberi
nal
ist
.

Al
gor
ith
m:

St
ep1:St
art

St
ep2 :I
nit
ial
izet
hev
alu
eofmi
nimu
m= 0

St
ep3:En
tert
hei
npu
tnu
mber(
n)o
fit
emsi
nal
ist
.

Step4 :Getallth
eel emen
tsusi
ngf o
rl o
opan
ds t
orei
t
inal i
st.St
ep5:Ass
ignthefir
stelementinali
stas
mini
mum.
Step6:Co mp
aremaxi
mumwit
hth
ef ir
stelementi
na
li
st,
n.Step7:Repea
ts t
ep8,
9unti
llistb
ec o
mes
empty.

St
ep8 :I
fnisl
esstha
nt he
mi
nimu
mSt
ep9:Ass
ignmin
imum= n

St
ep1
0 :Di
spl
aymin
imu
m

Ps
eudo
code:

BEGI
N

SET
nu
mli
st=[]
GET n

FOR i
=1t
on

GET n
uml
ist
el
emen
tsENDFOR

SET mi
nimu
m= n uml
ist
[0]
FOR iinnuml
ist

I
F(n<min
imum)
min
imum= n

ENDI F
ENDFOR
PRINT mi
nimum
END
UNI
TII

DATA,EXPRESSI
ONS,STATEMENTS

PART- A (
2 Ma
rks
)

1
.Wh
ati
smea
ntbyi
nter
pret
er?

Anint
erp
reterisacomputerp
rog
ramthatexecut
esi n
stru
cti
onswr
ittenina
p
rogr
ammingl
angu
age.Itcaneit
herexec
utethesour
cec odedirect
lyortra n
sla
tethe
s
our
cec o
deinaf irs
tstepin
toamo reeff
ici
entrepr
esenta
tionandexec
utest hi
sco
de.

2.Ho
wwi
llyo
uin
voket
hep
yth
oni
nter
pret
er?

ThePytho
nin
ter
pret
erc anbein
vokedbytypi
ngtheco
mma
nd"
pyt
hon
"wi
tho
uta
ny
p
ara
met
erfol
lowedbythe"ret
urn"k
eya tthes
hellpro
mpt
.

3.Wh
ati
smea
ntbyi
nter
act
ivemo
deo
fth
ein
ter
pret
er?

I
nterac
tivemodeisac o
mmandli
nes h
ellwhi
chgiv
esimmediat
efeedbackforea
ch
s
tatement,whil
er un
nin
gprev
iou
slyfedsta
tement
sinact
ivememory.Asn
ewl inesa
refed
i
ntot h
ei nter
preter
,thefedprog
ramiseval
uat
edbothinpar
ta ndinwhole.

4.Wr
iteas
nip
pett
odi
spl
ay“
Hel
loWo
rld”i
npyt
honi
nter
pret
er.

I
nsc
rip
tmo
de:

>>>pri
nt"
Hel
lo
Worl
d"Hel
loWorl
d

I
nIn
ter
act
iveMo
de:

>>>"Hel
loWorl
d"
'
Hell
oWo rl
d'

5.
Wha
tisav
alu
e?Wh
ata
ret
hedi
ffer
entt
ypeso
fva
lues
?
Avalueison
eo fth
efun
damentalt
hing
s— likealettero
ranumber— t
hatap
rog
ram
ma
nip
ulat
es.It
styp
esar
e:integ
er,fl
oat,b
ool
ean,s
tri
ngsan
dli
sts
.

6.Def
ineav
ari
abl
ean
dwr
itedo
wnt
her
ulesf
orn
ami
ngav
ari
abl
e.

Anamethatreferstoav al
ueisav ari
abl
e.Va r
iab
lenamesc a
nbearbi
trar
ilylon
g.
Theycanc
o n
tai
nb ot
hl ett
ersandnumber
s,buttheyh a
vet obeg
inwithalet
ter.Itis
leg
altous
eu pper
caseletter
s,b
uti ti
sg oo
dt ob eg
invari
abl
en ameswi
thalowerca
se
let
ter
.

7.Def
inekeywo
rda
nden
umer
ates
omeo
fth
ekeywo
rdsi
nPyt
hon
.

Akeywor
di sareservedwo r
dt hatisu
sedbyt
hecomp
ilert
op a
rseapro
gra
m.
Keywordscan
notbeuseda sv a
ria
blen ames
.Someo
fthek
eywordsu
sedinpyt
honar
e:
and,del,f
rom,not
,whil
e,is,conti
nue.

8.Def
ines
tat
emen
tan
dwh
ata
rei
tst
ypes
?

Ast
atemen
tisa ni
nst
ruc
tio
nthatthePyth
onint
erp
ret
erc
anex
ecu
te.Th
erea
re
t
wot
ypesofstat
emen
ts:pr
intandas
sig
nments
tat
emen
t.

9.Wh
atdoyo
umea
ntb
yana
ssi
gnmen
tst
atemen
t?

Ana s
sig
nmen
tsta
temen
tcrea
tesnewva
riabl
esandgi
vesthem
va
lues:Eg1:Mess
age= '
Andnowforsomet
hin
gcomp
letel
y
di
fferent
'

Eg2:n= 1
7

1
0.Wh
ati
stu
ple?

At upl
ei sas equen
c eo fi mmu
tablePythonobj
ects
.Tu p
lesa r
es equen
ces
,l i
kel ist
s.
Thediffer
encesb etweent uplesa ndlis
tsa r
e,thetupl
esc a
nnotbec ha
n g
edu nl
ikel i
sts
an
dt u
plesu s
ep arentheses
,wh ereasli
stsusesq
uarebrack
ets.Creat
ingat upleisass imple
aspu
ttin
gdi ffer
en tc o
mma -sep a
r a
tedvalues
.Comma-s
eparat
edv al
uesbetweenp ar
entheses
canal
sob eu s
ed.

Ex
amp
le:t
up1= (
'ph
ysi
cs'
,'c
hemi
str
y',1
997,2000)
;

1
1.
Wha
tisa
nex
pres
sio
n?
Anex
pres
sio
nisac o
mb i
nat
iono
fva
lues
,va
ria
bles
,an
dop
era
tor
s.Anex
pres
sio
nis
ev
alu
atedus
ingass
ign
men
to per
ato
r.

Ex
amp
les
:Y=x+ 1
7

1
2.Wh a
tdoyoumea
nbya
nop
era
nda
nda
nop
era
tor
?Il
lus
tra
teyo
ura
nswerwi
th
r
elev
antex
amp
le.

Anop
era
torisas ymbolthatspeci
fiesano per
atio
nt ob ep er
formedonthe
op
eran
ds.Th
eda t
aitemst h
ata noper
a t
ora ct
su po
na rec a
lledo pera
nds.Theopera
tor
s+,
-,*,/and**per
for
ma dditi
on,su
btra
c t
ion,mult
ipl
icati
on,divi
sio
na ndex p
onen
tia
tio
n.
Ex
amp
le:20+32

I
nth
isex
amp
le,20 a
nd32 a
reo
per
andsa
nd+ i
sano
per
ato
r.

1
3.Wh
ati
sth
eor
deri
nwh
icho
per
ati
onsa
reev
alu
ated?Gi
vet
heo
rdero
fpr
eceden
ce.

Thesetofr ulest
hatg o
vernth
eo rderinwh i
chex pr
essi
onsinv
olv
ingmulti
ple
o
per
ato
rsandoperandsareevalu
atedisknowna srul
eo fp r
ecedenc
e.Parenth
eseshave
t
hehig
hestpr
ecedencefoll
owedb yexpon
entia
tion
.Mu l
tipl
icati
onanddivis
ionhavethe
n
exthi
ghes
tprecedencefol
lowedb yaddi
tionands u
btrac
tion.

1
4.I
llu
str
atet
heu
seo
f*a
nd+ o
per
ato
rsi
nst
rin
gwi
thex
amp
le.

The*oper
ato
rper
for
msr
epet
iti
ono
nst
rin
gsa
ndt
he+ o
per
ato
rper
for
ms
co
nca
ten
ati
onon

s
tri
ngs
.

Ex
amp
le:

>>>Hel
lo*
3

Ou
tpu
t: Hel
loHel
loHel
lo

>>>Hel
lo+Wo
rld

Ou
tpu
t:Hel
loWo
rld
1
5.Wh
ati
sth
esymbo
lfo
rco
mmen
t?Gi
vea
nex
amp
le.

#isthesymbolf
orc
ommen
tsi
n
Pyth
on.Examp
le:

#c
omp
utet
hep
erc
ent
ageo
fth
eho
urt
hath
asel
aps
ed

1
6.Wh
ati
sfu
nct
ionc
all
?

Afu
ncti
oni san
a medsequen
c eofstatement
st hatp
erf
ormsacompu
tat
ion
.Wh
enwe
defi
neafun
ction
,wespecif
yt h
en a mean
dt h esequen
ceofstat
emen
ts.La
ter
,wecan
“ca
ll”t
hefunc
tionbyi
tsn amecalledasf u
nc t
ioncall
.

1
7.I
den
tif
yth
epa
rtso
faf
unc
tio
nint
heg
ivenex
amp
le.

>>>b
ett
y= t
ype(
"32"
)
>>>p
rin
tbet
ty

Then a
meo ft h
ef unc
tio
nistype,an
di tdispl
a ysthetypeo fav a
lueo rva
ria
ble.The
va
lueo rvar
iable,whi
chiscal
ledthea rg
umento fthef un
cti
on,isencl
osedinparent
heses.
Thea r
gumentis32.Th efu
ncti
onretur
nst h
er esul
tc a
lledretur
nv al
ue.Thereturnval
u e
i
ss t
oredinb etty.

1
8.Wh
ati
sal
oca
lva
ria
ble?

Avari
abledef
inedi
nsi
deaf
unc
tio
n.A l
oca
lva
ria
blec
ano
nlyb
eus
edi
nsi
dei
ts
f
unc
tion
.

1
5.Wh
ati
sth
eou
tpu
toft
hef
oll
owi
ng?

a
.fl
oat
(32)
b
.fl
oat
("3.
1
4159"
)

Ou
tpu
t:

a
.32.0 Theflo
atf
unc
tio
nc on
vert
si n
tegerstof
loat
ing
-po
int
n
umber
s.b.3.
141
59Thefloa
tf un
ctio
nc o
n v
ert
sstr
ing
st of
loat
ing
-
p
oin
tn u
mbers
.
1
6.Wh
atdoyo
umea
nbyf
lowo
fex
ecu
tio
n?

Inor
dertoen s
uret h
a tafunct
ionisdefi
nedbefo
reitsfi
rstus
e,wehavetoknow
th
eo rderi
nwh i
chs t
atementsareexecut
ed,whi
chiscal
ledt h
eflowofexecu
tio
n.
Exec
utiona
lwaysbegin
sa tthef i
rststat
emento
ft h
ep r
ogra
m.Stat
ementsa
reexecu
ted
on
ea tat i
me,inorderf r
omt optob o
ttom.

1
7.Wr
itedownt
heo u
tpu
tforthef
oll
owi
ng
pr
ogr
am.f
irs
t= 't
hro
at'

s
econd=
'
warbl
er'pri
nt
f
irs
t+ s ec
ond

Ou
tput:
th
roatwa
rbl
e
r

1
8.Gi
vet
hes
ynt
axo
ffu
nct
iondef
ini
tio
n.

defNAME(LIST OF
PARAMETERS )
:STATEMENTS

1
9.Ex
pla
int
hec
onc
epto
ffl
oordi
vis
ion
.

Theo p
era
tio
nth
atdi
videst
won
umb
ersa
ndc
hop
sof
fth
efr
act
ionp
arti
skn
owna
s
f
loo
rdiv
isi
on.

20.Wh
ati
styp
eco
erc
ion
?Gi
veex
amp
le.

Auto
mat
icmeth
odtocon
ver
tbetweenda
tatyp
esisc
alledtyp
ec oer
cio
n.Fo
r
mat
hemat
icalop
era
tor
s,i
fan
yo neop
erandisafl
oat
,th
eotherisauto
mati
call
yconv
ert
ed
toflo
at.

Eg
:

>>>mi
nut
e= 59
>>>mi
nute/60. 0
0.9833333333
33

21
.Wr
iteama
thf
unc
tio
ntop
erf
orm √2 /2.

>>>ma
th.
sqrt
(2)/
2.0
0.707106781
18
7

22.
Wha
tismea
ntbyt
rac
eba
ck?

Al i
stofthefunc
tion
stha
ttell
su swh
atpro
gramfil
etheerr
orocc
urr
edin,a
n d
whatl
ine,andwha
tf u
ncti
onswer
eexecut
ingatt
het i
me.I
ta l
sos
howst
hel i
neo
fc ode
th
atcausedtheerr
or.

PART B (
16MARKS)

1
. Whatistherol
eofanin
terpret
er?Gi
veadet
ail
edn
oteo
npyt
honi
nter
pret
er
an
di n
ter
acti
vemodeo
fo per
atio
n.

Aninter
pret
erisac o
mpu
terprogr
amt
hatex
ecu
tesi
nst
ruc
tio
nswr
itt
eni
na
p
rog
ramminglan
gua
ge.Itcanei
ther

 ex
ecu
tet
hes
our
cec
odedi
rec
tlyo
r

 tr
a n
slat
esthes
ourc
eco
dei
naf
irs
tst
epi
ntoamo
reef
fic
ien
trep
res
ent
ati
ona
nd
execut
esth
iscode

Pyth
oni
nter
pret
era
ndi
nter
act
ive
mode
WiththePyt
honint
eract
ivein
ter
pret
eri tisea
sytochec
kPythonc
omman
ds.ThePyt
hon
i
nter
pret
erca
nb einvo
kedb ytyp
ingthec o
mmand"p
yth
on"wi
tho
utanypa
ramet
er
f
ollo
wedb yt
he"retur
n"keya tth
es hel
lp r
omp
t:

$p
yth
on

>>>

OncethePyt
honint
erp
ret
eriss
tar
ted,youc
aniss
ueanycomma
nda
tth
eco
mma
ndp
romp
t
">>>"
.Forex
ampl
e,l
etuspri
ntt
he"HelloWo
rld"s
tat
emen
t:

>>>pri
nt"
Hel
lo
Worl
d"Hel
loWorl
d

I
nth
ein
ter
act
ivePyt
honi
nter
pret
ert
hep
rin
tisn
otn
eces
sar
y:

>>>"
Hel
loWo
rld"

Hel
loWo
rld'

>>>
33

>>>

Typin
ga nend-of-f
ilec ha
racter(Ctrl
+D onUn i
x,Ctrl+Z onWi
ndows)a
tthepr
imar
y
pr
omptc a
usestheinterp
retertoex i
twi thazeroex i
ts t
atus
.Ifth
a tdo
esn
two
rk,youc
an
exi
tt heint
erp
reterb ytypin
gt hefollowi
ngcommand:q u
it(
).

Whenc
omma
ndsa
rer
eadf
rom at
ty,t
hei
nter
pret
eri
ssa
idt
ob ni
ei n
ter
act
ivemo
de.I
n
th
ismo
deit
p
romp
tsfort
hen
extc
omma
ndwi
tht
hep
rima
ryp
romp
t,u
sua
llyt
hreeg
rea
ter
-th
ans
ign
s
(
>>>);f
or

c
onti
nuat
ionl
inesi
tpr
omp
tswi
tht
hes
eco
nda
ryp
romp
t,b
ydef
aul
tth
reedo
ts(
..
.)
.Th
e
i
nter
pret
er

p
rin
tsawel c
omemes
sag
est
ati
ngi
tsv
ers
ionn
umb
era
ndac
opyr
igh
tno
tic
ebef
orep
rin
tin
g
t
hef i
rstp
rompt
:

Cont
inu
ati
onli
nesareneededwh
enen
ter
ingamu
lti
-li
nec
ons
tru
ct.Asa
nex
amp
le,t
akea
lo
oka tthi
si fst
atemen
t:

>>>t
he_
wor
ld_
is_
fla
t= 1

>>>i
fth
e_wo
rld_
is_
fla
t:

.
.
. p
rin
t"Bec
aref
uln
ott
ofa
llo
ff!
"
2.(
a)Li
stdo
wnt
her
ulesf
orn
ami
ngt
hev
ari
abl
ewi
thex
amp
le.

Avari
a b
leisanametha
tr efer
stoav
alu
e.Ana
ssi
gnmen
tst
atemen
tcr
eat
esn
ew
v
ari
ablesan
dgiv
est h
em va
lues:

Var
iabl
en a
mesc a
nbearb
itr
ari
lylong.Th
eycanc
ont
ainb
othlett
ersandnumber
s,
bu
tt h
eyh avetobeg
inwi
thal et
ter
.I ti
sleg
alt
ou s
eupper
cas
el et
ter
s,b
u titis
agoodideat o

b
egi
nva
ria
blen
ameswi
thal
ower
cas
elet
ter.

Theun
dersc
orec
h a
ract
er,_
,canapp
eari
nan ame.Itiso
ftenu
sedi
nna
mes
wi
thmult
ipl
ewords,s
uchasmy_n
ameorvar
iab
le_n
ame.

I
fyo
ugi
veav
ari
abl
eani
lleg
aln
ame,yo
ugetas
ynt
axer
ror
:

(
b)Li
stdo
wnt
hedi
ffer
entt
ypeso
fop
era
tor
swi
ths
uit
abl
eex
amp
les
.
3.Whatdoyoumea
nbyrul
eofp r
eceden
ce?Li
sto
utt
heo
rdero
fpr
eceden
cea
nd
demon
str
atei
ndeta
ilwi
thex
ample.

Whenmoretha
no neoper
ato
rappea
rsina nexpres
sio
n,theorderofeval
uat
iondep
endso
n
t
herul
eso fp
recedenc
e.Format
hemati
calo p
era
tors
,Pythonfoll
owsmath
emati
cal
c
onv
ent
ion
.Thea cr
onymPEMDAS isau sef
ulwayt oremembertherul
es,

• Pa ren
theseshaveth
eh i
ghes
tprec
edencean
dcanbeu s
edtofor
cean
ex
press
iontoeva l
uat
ei ntheor
deryo
uwa nt
.Sin
ceex
pres
sio
nsinpa
rent
hes
esa
re
ev
alua
tedf i
rst,

2 *(
3-1
)is4,a
nd(
1+1
)**
(5-2)i
s8.

Youcana
lsous
ep ar
ent
hesest
omakeanex
pres
sio
nea
siert
orea
d,a
sin(
min
ute*1
00)
/60,ev
enifitdoes
ntchan
g et
her
esul
t.

•Expo
nen
tia
tio
nha
sth
enex
thi
ghes
tpr
eceden
ce,s
o2*
*1+1i
s3,n
ot4 a
nd3*
1**
3is3,
no
t27.

•Mult
ipli
cat
ion a
nd Di
vis
ion h
ave t
he s
ame p
rec
eden
ce, wh
ich i
shi
gher t
han
Addit
ion and

Subt
rac
tio
n,wh
icha
lsoh
avet
hes
amep
rec
eden
ce.So2*
3-1i
s5,n
ot4,a
nd6+4/
2is8,
no
t5.

•Operat
orswiththes
amep
rec
eden
cea
reev
alu
atedf
roml
eftt
ori
ght(
exc
ept
ex
p o
nenti
ati
on).

Soi nth
eexpres
sio
ndegrees/2 *p i
,thediv
isi
onhap
pen
sfir
stan
dt heres
ulti
s
mu
lti
pli
edb yp
i.Todi v
ideb y2 ,yo
uc anus
ep ar
ent
hes
esorwri
tedeg
rees/2 /p i
.
4. Ex
pla
int
her
oleo
ffu
nct
ionc
alla
ndf
unc
tio
ndef
ini
tio
nwi
thex
amp
le.

Af un
cti
onisan amedsequ
enceofs
tat
emen
tstha
tp erf
ormsacompu
tat
ion
.Wh enyou
defi
neaf u
ncti
on,youspec
ifythen
ameandth
es eq
u en
ceo fs
tat
ement
s.Lat
er ,yo
u
can“cal
l”thefunct
ionbyname.

>>>
type(
32)
<type'i
nt'
>

Then ameo fthefu


nct
ionistype.Theexpress
ioninp ar
ent
hes
esiscal
ledth
e
arg
umento fthefun
cti
on.Theresul
t,forthisfunc
tion
,isthetypeofthear
gumen
t.
Af un
ction“tak
es”anargu
mentand“ r
etur
ns”ar esu
lt.Theres
ultisca
lledt
he
ret
urnv a
lue.

Typ
eco
nver
sio
nfu
nct
ion
s

Pyth
onpr
ovi
desbui
lt-inf
unc
tionst
hatco
nver
tvalu
esf r
omon
et yp
etoanot
her
.Theint
fu
ncti
ont
akesan
yv alu
eandc o
nver
tsittoanin
teger
,ifitcan
,orco
mpl
ain
sother
wis
e:

>>>i
nt(
'32'
)

32

>>>i
nt(
'Hel
lo'
)

Va
lueEr
ror
:in
val
idl
iter
alf
ori
nt(
):Hel
lo

i
ntcanco
nver
tf l
oat
ing
-po
intva
luest
oin
teg
ers
,bu
titdo
esn
tro
undo
ff;i
t
c
hopsoffthefra
cti
onpar
t:

>>>
in
t(3.
99999)3
>>>i
nt(
-
2.
3)-2

f
loa
tco
nver
tsi
nteg
ersa
nds
tri
ngst
ofl
oat
ing
-po
intn
umb
ers
:

>>>f
loa
t(32)

32.
0

>>>f
loa
t('
3.
141
59'
)

3.
1
4159

Fi
nal
ly,s
trc
onv
ert
sit
sar
gumen
ttoas
tri
ng:

>>>s
tr(
32)

32'

>>>s
tr(
3.1
4159)

3.
1
4159'

5. Howdoyo
umakeuseofma
thf
unc
tio
nsi
n
Pyt
hon
?Mathf
unc
tio
ns

Pyth
onh asamat
hmodu
letha
tp ro
videsmos
toft h
ef ami
lia
rma t
hemati
cal
fu
ncti
ons
.A modu
lei
saf i
letha
tc onta
insaco
llect
ionofrela
tedf u
ncti
ons
.

Bef
orewec
anu
set
hemo
dul
e,weh
avet
oimp
orti
t:

>>>i
mpo
rtma
th
Thiss
tat
emen
tcreat
esamo du
leobj
ectnamedma
th.I
fyo
upr
intt
hemo
dul
e
ob
ject
,yougets
o mein
for
mati
ona
boutit
:

>>>p
rin
tma
th

<mo
dul
e'ma
th'(
bui
lt-i
n)>

Themoduleobj
ectcon
tainsthef u
ncti
onsan
dv a
riab
lesdefi
nedi
nthemo
dule.
Toacces
so n
eo fth
ef un
ctio
ns,
speci
fyt h
en a
meo fthemodul
eandt
hename
ofth
e

fu
nct
ion,s
epara
tedb
yado
t(a
lsok
nowna
sap
eri
od)
.Th
isf
orma
tisc
all
ed
dotnot
ati
on.

>>>r
ati
o= s
ign
al_
power/n
ois
e_p
ower

>>>dec
ibel
s= 1
0 *ma
th.
log
10(
rat
io)

>>>r
adi
ans= 0.
7

>>>h
eig
ht= ma
th.
si
n(r
adi
ans
)

Thefirstexampl
eu seslog1
0t ocomputeasi
gnal
-to
-n oi
serat
ioi
ndec
ibel
s
(a
ssu
mingt hats
igna
l_ po
werandn o
ise_p
owera
redefined).Th
emathmo
dule
al
sop r
ovideslo
g,whi c
hc o
mp u
tesloga
rith
msbas
ee.

Thesecondexamp
lef i
ndsthesin
eo fradi
ans
.Th ena
meo ft hevar
iab
lei
sa
hi
ntthatsinandtheo t
hertri
gono
metr
icfunc
tio
ns(cos
,t a
n,etc.
)take
ar
gument
si nr
adians
.Toc o
nver
tf r
omdeg r
eestoradi
ans,div
ideby360 a
nd
mul
tip
lyb y2 :
>>>deg
rees= 45

>>>r
adi
ans= deg
rees/360.
0 *2 *ma
th.
pi

>>>ma
th.
si
n(r
adi
ans
)

0.
7071
06781
187

Theexpr
ess
ionmath.
pig
etst
hev a
ria
blepifr
omthemathmo
dul
e.The
va
lueofthi
sv a
ria
bleisanapp
rox
imati
onof ,a
ccu
rat
et oa
bou
t15
di
git
s.

>>>math
.sq
rt(2)/
2.
0
0.
7071
06781187

6. Wr
iteaPyt
honp
rog
ramt
oswa
ptwov
ari
abl
es.

x= 5

y= 1
0

#crea
teat emp
ora
ryv
ari
abl
ean
dswa
pth
e
va
luestemp= x

x= y

y= t
emp

p
rint
("Thevalu
eo fxaft
er
s
wappin
g:”
,x)
)p rin
t("
Theval
ueo
fy
a
fterswappi
ng:
”,y))

7. Writ
eaPyt
honp
rog
ramt
och
eckwh
eth
erag
ivenyea
risal
eapyea
ror
no
t.

#Tog
etyea
r(i
nteg
eri
npu
t)f
romt
heu
ser
yea
r= in
t(i
npu
t("
Ent
era
yea
r")
)if(yea
r% 4)==
0:

i
f( yea
r% 100)==
0:if(yea
r%
400)== 0:

p
rint
("%disalea
p
year
"%year
)els
e:

p
rin
t("
%di
sno
tal
eapyea
r"%d)

el
se:

p
rin
t("
%di
sal
eapyea
r"%yea
r)

el
se:

p
rin
t("
%di
sno
tal
eapyea
r"%yea
r)

8. Wr
iteaPyt
honp
rog
ramt
oco
nver
tcel
siu
stof
ahr
enh
eit.

(
For
mul
a:c
els
ius*1
.
8 =f
ahr
enh
eit—32)
.

#Pyt
honPr
ogr
amt
oco
nver
ttemp
era
tur
einc
els
iust
ofa
hren
hei
t

#c
han
get
hisv
alu
efo
radi
ffer
entr
esu
lt

c
els
ius= 37.
5

#c al
culat
efa
hrenh
eit
f
ahrenhei
t= (
cels
ius*1.
8)
+ 32

p
r i
nt('
%0.1
fdegreeCelsi
usi
seq
ualt
o%0.
1
fdeg
reeFa
hren
hei
t'
%(cel
siu
s,f
ahr
enhei
t))
UNI
TII
I

CONTROL FLOW,FUNCTI
ONS

PART- A (
2 Ma
rks
)

1
.Def
ineBo
olea
nex
pres
sio
nwi
thex
amp
le.

Abo
olea
nex p
res
sionisanexpr
ess
iont
hati
sei
thert
rueo
rfa
lse.Th
eva
luest
ruea
nd
f
als
ear
ec al
ledBooleanva
lues
.

Eg:

>>>5
== 6
Fal
se

Tr
uea
ndFa
lsea
res
pec
ialv
alu
est
hatb
elo
ngst
oth
etyp
ebo
ol;t
heya
ren
ots
tri
ngs
:

2.
Wha
tar
eth
edi
ffer
entt
ypeso
fop
era
tor
s?

 Ar
ith
met
icOp
era
tor(
+,-,*
,/,%,*
*,/
/)

 Rel
ati
ona
lop
era
tor (== ,!
=,< >,<,>,<=,>=)

 As
sig
nmen
tOp
era
tor(=,+= ,*
= ,- =,/
=,%= ,
**
=)

 Lo
gic
alOp
era
tor(
AND,OR,NOT)

 Memb
ers
hipOp
era
tor(
in,n
oti
n)

 Bit
wis
eOpera
tor(&(an
d),|(or
),^(bin
aryXo
r),~(
bin
ary1
sco
mpl
emen
t,<<
(b
inar
ylef
tshif
t),>>(bi
nar
yrigh
tsh
ift)
)

 I
den
tit
y(i
s,i
sno
t)

3.
Exp
lai
nmo
dul
uso
per
ato
rwi
thex
amp
le.
Themodu l
usoper
ato
rwo r
kso nin
tegersandyiel
dstheremai
nderwhent h
ef i
rst
op
era
ndi sdi
videdbyt hesec
ond.InPython,th
emo dul
uso
pera
t o
risap er
c en
ts i
gn(%).
Thesyn
taxist h
es a
mea sforotherop
erat
o r
s:
Eg
:

>>>r
ema
inder= 7% 3

>>>p
rin
trema
inder

So7di
videdb
y3i
s2 wi
th1l
efto
ver
.

4.Ex
pla
inr
ela
tio
nalo
per
ato
rs.

The== oper
ato
riso
neoft
herela
tio
nalo
per
ato
rs;t
he
ot
her
sare:X!= y# xi
snoteq
ualtoy

x>y# xi sg
rea
ter
t
hanyx<y# xi s
l
esst
hany

x>= y# xi sgr
eat
ert
hanor
equa
ltoyx<= y# xi sles
s
th
ano req
ualtoy

5.Ex
pla
inLo
gic
alo
per
ato
rs

Therear
et hreelogicalop
era t
ors:and,or,andn o
t.Forexamp
le,x>0 a ndx<1 0
istru
eo nlyifxi sg r
eatert h
an0 a ndl es
sth a
n1 0.n%2 == 0 o
rn%3== 0 ist r
ueif
eit
hero fthecondit
ionsist r
ue,tha
ti s,ifthen umberisdiv
isi
bleby2 or3.Final
ly,th
e
notoperato
rnegatesaBo oleanexpressi
on,sonot(x>y)i st
rueifx>yi sfal
se,tha
tis,
ifxi slessth
ano req u
altoy.No n-z eronumberiss a
idt obetrueinBoo
lea
nex pr
ess
ion
s.

6.Wh
ati
sco
ndi
tio
nalex
ecu
tio
n?

Theabi
lit
ytoc hec
kt hecondi
tionandc
han
get
heb
eha
vio
roft
hep
rog
rama
cco
rdi
ngl
yis
ca
lledcon
dit
ion
alex ec
uti
on.Exampl
e:
I
fst
atemen
t:

Th
esi
mpl
estf
ormo
fifs
tat
emen
tis
:

Synt
ax:
if

s
tat
emen
t:

Eg
:

i
fx>0:

p
rin
t'xi
spo
sit
ive'

Th
eb oo
lea
nexpres
sio
na ft
erifi
scall
edt h
ec on
diti
on.I
fiti
str
ue,t
hent
he
i
nden
tedsta
tementg
etsexecut
ed.Ifno
t,n
othin
gh ap
pens
.

7.Wh
ati
sal
ter
nat
iveex
ecu
tio
n?

Asec
ondf or
mo fi
fst
atementi
sa lt
ern
ati
veexec
uti
on,tha
tis,if…else,wh
eret
her
e
a
retwop o
ssi
bil
iti
esa
ndthec o
ndi
tio
ndetermin
eswhi
cho n
et oexec
ute.

Eg
:

i
fx%2 == 0:

p
rin
t'xi
sev
en'

el
se:

p
rin
t'xi
sodd'

8.Wh
ata
rec
hai
nedc
ondi
tio
nal
s?
Somet
imesth
erearemor
et ha
nt wopo
ssib
ili
tiesan
dwen eedmor
et ha
nt wo
b
ran
ches.Onewa ytoex
pres
sac o
mp u
tati
onli
ket ha
ti sach
ain
edc o
ndi
tio
nal:

Eg
:

i
fx<y:

pri
nt'xi
sles
s
t
hany'eli
fx>y:

p
rin
t'xi
sgr
eat
ert
hany'

el
se:

p
rin
t'xa
ndya
reeq
ual
'

el
ifi sana b
brev
iati
ono
f“ el
sei
f.”Agai
n,exa
ctlyon
ebran
chwi
llbeexec
uted.Th
erei
s
nolimitonthen u
mberofeli
fsta
tement
s.Ifther
eisanels
ecl
aus
e,i
th a
st obeatth
e
end,buttheredoesn
thavetobeone.

9.Expl
ainwhi
lel
oopwi
th
examp
le.Eg:

defc
ount
down
(n)
:
wh
ilen>
0:

pr
intn
n= n
-1

p
rin
t'Bl
ast
off
!'

Mo
ref
orma
lly,h
erei
sth
efl
owo
fex
ecu
tio
nfo
rawh
iles
tat
emen
t:

1
.Ev
alu
atet
hec
ondi
tio
n,yi
eldi
ngTr
ueo
rFa
lse.

2.
Ift h
econdi
tio
nisf
als
e,ex
itt
hewh
iles
tat
emen
tan
dco
nti
nueex
ecu
tio
natt
hen
ext
sta
temen
t.

3.
Ift
hec
ondi
tio
nist
rue,ex
ecu
tet
heb
odya
ndt
heng
oba
ckt
ost
ep1

9.Ex
pla
inf
orl
oopwi
thex
amp
le.

Th
egen
era
lfo
rmo
faf
ors
tat
emen
tis
Syn
tax
:

f
orv
ari
ablein
s
equen
ce:c
ode
bl
ock

Eg:
x=
4

f
oriinra
nge(
0,
x
):pr
inti

1
0.Wh
ati
sabr
eaks
tat
emen
t?

Whenabr
eaks
tat
emen
tisenc
ount
eredin
sideal o
op,theloo
pisimmedi
ately
t
ermi
natedan
dthepr
ogr
amcont
rolr
esu
mesa tt
hen ex
ts t
atemen
tfoll
owi
ngthel o
op.

Eg
:

wh
ileTr
ue:

l
ine=
r
aw_i
npu
t('>'
)if
l
ine== 'don
e':

b
reak
p
rin
t
l
ine

p
rin
t'Do
ne!
'

1
1.Wh
ati
sac
ont
inu
est
atemen
t?

Thecont
inuest
atemen
twork
ssomewh
atli
keabrea
ks t
atemen
t.Ins
tea
do ff
orc
ing
t
ermi
nati
on,i
tf or
cesthenexti
ter
ati
onoftheloo
ptotakepla
ce,ski
ppi
nganyco
dei n
b
etween.
Eg
:

f
ornumin
r
ang
e(2,
10)
:if
n
um%2==0;

p
rin
t“Foundanev
enn
umb
er”
,
n
umc o
nti
nue

p
rin
t“Fo
undan
umb
er”
,nu
m

1
2.Compar
er et
urnva
lueand
c
ompo
sit
ion.Retu
rnValu
e:

Retu
rngiv
esbac
ko rr
epl
iestothec
allero
ft hefu
ncti
on.Ther
etu
rns
tat
emen
t
c
aus
esourfun
cti
ont
oex i
tandhandov
erbackavalu
et oitscal
ler
.

Eg
:

defa
rea
(ra
diu
s):

temp= ma
th.p
i*
r
adi
us*
*2ret
urntemp

Co
mpo
sit
ion
:

Ca
lli
ngo
nef
unc
tio
nfr
oma
not
heri
sca
lledc
omp
osi
tio
n.

Eg
:

defc
irc
le_
area
(xc
,yc
,xp
,yp
):

ra
diu
s= dist
ance(
xc,yc,xp
,
yp)res
ult= ar
ea(ra
diu
s)

r
etu
rnr
esu
lt

1
3.Wh
ati
srec
urs
ion
?

Thepro
cessi
nwh i
chaf u
ncti
onca
llsits
elfdi
rec
tlyo ri
ndi
rectl
yisc
all
ed
r
ecu
rsi
onan
dt heco
rres
pondi
ngfun
cti
oni
sc a
lledasrecu
rsi
vefunc
tio
n.
Eg
:

def
f
act
ori
al(
n):
i
fn== 1 :

retur
n
1els
e:

r
etu
rnn*f
act
ori
al(
n-1
)

1
4.Ex
pla
ing
loba
lan
dlo
cals
cop
e.

Thes c
opeo fav a
ria
blerefer
stot h
ep lac
est ha
twec a
ns eeora cces
sav ar
iabl
e.
I
fwedef i
neav ari
ableont h
etopo fth
es cri
pto rmodul
e,thev ar
iab
lei scalledg l
obal
v
ari
abl
e.Thev a
ria
blesthataredefi
nedinsi
deac la
ssorf u
ncti
onisc al
ledl oc
a l
v
ari
abl
e.

Eg
:

defmy_
loc
al(
):
a
=10

p
rin
t(“
Thi
sisl
oca
lva
ria
ble”
)

Eg
:

a
=10

defmy_
glo
bal
():

p
rin
t(“
Thi
sisg
lob
alv
ari
abl
e”)
1
5.Co
mpa
res
tri
nga
nds
tri
ngs
lic
es.

As
tri
ngi
sas
equ
enc
eofc
har
act
er.

Eg
:fr
uit= b
ana
na

St
rin
gSl
ices:

Aseg
mentofast
rin
gisc
all
edstr
ings
lic
e,s
elec
tin
gas
lic
eiss
imi
lart
o
s
elec
tin
gac ha
rac
ter
.Eg
:>>>s='Mon
tyPyth
on'

>>>pri
nt
s[
0:5]Mont
y

>>>pri
nt
s[
6:1
2]Pyth
on

1
6.Def
ines
tri
ngi
mmu
tabi
lit
y.

Pyt
honst
rin
gsar
ei mmut
abl
e.aisno
tas t
rin
g.I
tisav
ari
abl
ewit
hs t
rin
gv alu
e.
Wec
antmuta
tethest
rin
gb utcanch
ang
ewh a
tvalu
eofth
eva
ria
bletoanews t
rin
g.

Pr
ogr
am: Ou
tpu
t:

a= “
foo
” #f
oof
oo

# an
owp
oin
tst
ofo
o #f
oo

It i
sob
ser
ved t
hat b h
asn
t c
han
ged
b
=a ev
en

# bno
wp o
int
stot
hes
amef
oot
hata
p
oin
tsto t
hou
ghah
asc
han
ged.

a
=a+a

# apoi
ntst
oth
enews
tri
ng“
foo
foo
”,b
ut
bpoi
nts

t
oth
esa
meo
ld“
foo

p
rin
ta

p
rin
tb
1
7.Menti
onafewstr
ingf u
nct
ions
.
s
.cap
tili
ze(
)— Ca
pital
izesfi
rstcha
rac
ter
o
fs tri
ng

s
.co
unt
(su
b)— Co
untn
umb
ero
foc
cur
ren
ceso
fsu
bins
tri
ng

s.
lower
()— c o
nvert
sas t
rin
gt olower
cas
es .
spl
it(
)— r etur
nsalistof
wordsinstr
ing

1
8.Wh
ata
res
tri
ngmet
hods
?

A meth
odi ssimil
art oafu
ncti
on—itt
akesar
gumen
tsa
ndr et
urn
sav al
ue—bu
tthe
syn
taxisdiff
erent
.Fo rexampl
e,themeth
odu p
pertak
esastr
ingandret
urn
san ewst
rin
g
wit
ha l
lu p
perca
sel ett
ers:
I
nst
eado
fth
efu
nct
ions
ynt
axu
pper
(wo
rd)
,itu
sest
hemet
hods
ynt
axwo
rd.
upp
er(
)

.
>>>wo
rd= '
ban
ana
'

>>>n
ew_
wor
d= wo
rd.
upp
er(
)

>>>pri
ntn
ew_
wor
d
BANANA

1
9.Ex
pla
ina
bou
tst
rin
gmo
dul
e.

Thes
tri
ngmo
dul
ec on
tai
nsnumb
ero fusefu
lco
nst
ant
sa n
dc l
ass
es,aswel
lass
ome
dep
rec
a t
edleg
acyf
unc
tio
nsthata
rea ls
oa v
aila
blea
smethodsonstr
ing
s.

Eg
:

Pr
ogr
am: Ou
tpu
t:

up
per => MONTY PYTHON'
S
i
mpo
rts
tri
ng FLYI
NG
t
ext= "
Mon
tyPyt
hon
'sFl
yin
gCi
rcu
s" CI
RCUS
l
ower=>mo
ntyp
yth
on'
sfl
yin
gci
rcu
s
p
rin
t"u
pper
","
=>"
,st
rin
g.u
pper
(tex
t)
s
pli
t=>[ '
Mon
ty'
,"Pyt
hon
's"
,'Fl
yin
g',
'
Cir
cus
']
p
rin
t"l
ower
","
=>"
,st
rin
g.l
ower
(tex
t)
j
oin=>Mo
nty+Pyt
hon
's+Fl
yin
g+Ci
rcu
s
p
rin
t"s
pli
t","
=>"
,st
rin
g.s
pli
t(t
ext
)
r
epl
ace=>Mo
ntyJa
va'
sFl
yin
gCi
rcu
s
p
ri "
join
", s
tri
ng.
joi
n(s
tri
ng.
spl
it(
te
n
t "=>", xt),
"
+" f
ind=>6-1
)
c
oun
t=>3
p
ri
n
t "r
epl
ace"
, "
=>"
,s
tri
ng.
rep
lac
e(t
ext
,

"
Pyt
hon
","
Jav
a")

p
rin
t" fin
d","
=>"
,st
rin
g.f
ind(
tex
t,
"
Pytho
n")
,

s
tri
ng.
fi
nd(
tex
t,"
Jav
a")

p
rin
t"c
oun
t","
=>"
,st
rin
g.c
oun
t(t
ext
,"n
")

20.Wh
ati
sth
epu
rpo
seo
fpa
sss
tat
emen
t?

Us
ingap
asss
tat
emen
tisa
nex
pli
citwa
yoft
ell
ingt
hei
nter
pret
ert
odon
oth
ing
.

Eg
:

defb
ar():
p
ass

I
fth
efu
nct
ionb
ar(
)isc
all
ed,i
tdo
esa
bso
lut
elyn
oth
ing
.

PART B (
16MARKS)

1
.Ex
pla
int
ypeso
fop
era
tor
s.
i
)Ar
ith
met
icOp
era
tor
s

As
sumev
ari
abl
eah
olds1
0an
dva
ria
blebh
olds20,t
hen
-

Op
era
tor Des
cri
pti
on Ex
amp
le

Addsv
alu
eso
nei
ther
+ Addi
tio
n si
deof a+ b= 30
t
he
o
per
ato
r

Subt
ract
sri
ghth
and
-Su
btr
act
ion op
erand a— b= -1
0
f
romlef
tha
nd
o
pera
nd

Mult
ipl
ies o ei
th
*Mu
lti
pli
cat
ion va
lues n er a*b= 200
s
ideofthe
o
pera
tor

Di
videsl
efth
ando
per
and
/Di
vis
ion by b/a= 2
r
igh
th an
d
o
peran
d

Di
videsl
efth
ando
per
and
% Mo
dul
us
by
r
ig o
per
a
h
t ha
nd n
d a
nd
b% a= 0
r
etu
rns
r
emai
nder

Perfo
rms p
owe
*
*Ex
pon
ent exp
onent
ial r a
**b=1
0
c
alc
ula
tio
nono
per
ato
rs

Th di
vis
io o 9/
/ 2= 4 a
nd9.
0//
2.0
/
/Fl
oorDi
vis
ion e n fop
era
nds = 4.
0
wher
e t
he r
esu
lt i
s
th
e

qu
oti
ent i
nwh
icht
he
di
git
s

a
fter t
he dec
ima
l
p
ointare
r
emo
ved

i
i) Pyt
honCo
mpa
ris
onOp
era
tor
s

Theseo
perat
orsco
mpar
et hevalu
esoneit
hersi
desofthem a
nddec
idet
her
ela
tio
n
amon
gthem.Theyareals
oc a
lledRel
ati
onalo
pera
tor
s.

As
sumev
ari
abl
eah
olds1
0an
dva
ria
blebh
olds20,t
hen−

Op
era
tor Des
cri
pti
on Ex
amp
le
I
fthevalu
eso
ftwo
== o
per
ands a== bi
sno
ttr
ue

a
reequal,t
hent
he
c
ondi
tio
n

b
eco
mest
rue.

I
fval
ueso
ftwoo
per
ands
!
= a
re a
!=bi
str
ue
n equ th
o
t al
, en c
ondi
tio
n

b
eco
mest
rue.

I
fval
ueso
ftwoo
per
ands
<> a
re a<>bi
str
ue
n equ th
o
t al
, en c
ondi
tio
n

b
eco
mest
rue

I
ftheva
lueo
flef
t
> o
per
andi
s a>bi
sno
ttr
ue
g
reatert
hant
hev
alu
eof
r
igh
t

o
per
and,t
henc
ondi
tio
n

b
eco
mest
rue

I
ftheva
lueo
flef
t
< o
per
andi
s a<bi
str
ue

l
esst
han t
he v
alu
e
o
f r
igh
t

o
per
and, t
hen c
ondi
tio
n

b
eco
mest
rue

I
ftheva
lueo
flef
t
>= o
per
andi
s a>= bi
sno
ttr
ue
g
rea
tert
hano
req
ualt
o
t
he

v
alu
eofr
igh
top
era
nd,
t
hen

c
ondi
tio
nbec
omest
rue

I
ftheva
lueo
flef
t
<= o
per
andi
s a<= bi
str
ue
l
esstha
noreq
ualt
oth
e
v
alue

o r
igh o
per
and,
f t then

c
ondi
tio
nbec
omest
rue

(
iii
)Lo
gic
alo
per
ato
rs

Therearet h
reel ogi
calo p
erato
rs:a n
d,o r,andn o
t.Forexample,x>0 andx<1 0i s
tru
eo nl
yi fxi sg r
eaterthan0 andl essthan10.n%2 == 0 orn%3== 0 i
strueif
eit
heroft heconditi
onsist r
ue,thati s,ifthenumberisdivi
sibl
eby2 or3.Final
ly,the
notoper
a t
ornegatesaBo oleanexpression
,son o
t(x>y)i st r
uei fx>yi sfal
se,tha
ti s
,
ifxisl esstha
no req ua
lt oy.No nz eron u
mberiss a
idtob et r
ueinBo
olea
nex p
ress
ion
s.

(
iv) As
sig
nmen
top
era
tor
s
Des
cri
pti
o
Op
era
tor n Ex
amp
le

Ass
ign va
lu f
ro r
igh c= a+ ba
ssi
gnsv
alu
e
= s es m t o
fa+
s
ide o
per
ands t
o l
eft
s
ide bi
ntoc

op
era
n
d.

I
taddsr
igh
top
era
ndt
o c+= ai
seq
uiv
alen
tto
+= AddAND t
he c= c+
l
eft o
peran
d a
nd
a
ssi
gn th
e a

r
esu
ltt ol
eft
o
peran
d

Isu
btrac
t r
ig o
per
an c-= ai
seq
uiv
alen
tto
-= Su
btr
actAND t s h
t d c= c-
f
rom t
he l
efto
per
and
a
nd a

a
ssi
gn t h
e r
esu
lt
t
o l ef
t

o
per
an
d

I mu
lti
pli r
ig o
per
an c*= ai
seq
uiv
alen
ttoc
*
= Mu
lti
plyAND t es h
t d = c*

wi
th t
he l
eft o
per
and a
a
nd

a
ssi
gn t h
e r
esu
lt
t
o l ef
t

o
per
an
d

I
t div
ides lef
t c/= ai
seq
uiv
alen
ttoc
/
= Di
videAND o
per
and wit
h = c/
t
her i
ghto
per
anda
nd a
c/= aiseq
uiv
alen
tto
a
ssi
gn c= c/

t
heres
ultt
olef
t
o
per
and a

I
t ta
kes mo
dul
usu
sin
g c%= ai
seq
uiv
alen
tto
%= Mo
dul
usAND t
wo c= c
op
era
n a
n a
ssi
ds d g
n t
he %a

r
esu
ltt ol
eft
o
peran
d

Per
for ex
pon
entia
l c*
*= ai
seq
uiv
alen
tto
*
*= Ex
pon
entAND ms po
wer c= c
c
alc
ula
tio
nono
per
ato
rs
a
nd *
*a

a
ssi
gn v
alu
e t
o t
he
l
eft

o
per
an
d

I
tper
for
msf
loo
rdi
vis
ion c/
/= aiseq
uiv
alen
tto
/
/= Fl
oorDi
vis
ion o
n c= c/
/
o
per
ato
rsa
nda
ssi
gnv
alu
e
t
o a

t
hel
eft
o
per
and

2.Ex
pla
inc
ondi
tio
nala
lter
nat
ivea
ndc
hai
nedc
ondi
tio
nal
.

Th
esi
mpl
estf
ormo
fifs
tat
emen
tis
:

Syntax
:
if
st
atement
:
Eg
:

i
fx>0:

p
rin
t'xi
spo
sit
ive'

Th ebooleanex press
iona ft
eri fi scal
ledt hec ondit
ion.Ifi tist ru
e,thent h
e
in
den t
eds tatemen tgetsex ecut
ed.I fnot,nothinghappens.ifstatementshav
et he
sames tr
uctur
ea sf un
ctiondef i
niti
ons
:ah eaderf ol
lowedb ya nin dent
edb ody.
Statementsliket hisa recalledc ompo
unds tatement
s.Th ereisn ol i
mito nthe
numbero fstatemen t
st hatc a
na ppearint heb ody,butt her
eh ast ob ea tleas
to ne.
Occasion
ally,itisu s
efultoh a
veab odywit hn ostat
emen t
s. I
nt hatc a
se,youc a
n
us
et hep a
sss ta
temen t,whichdo esnothi
ng.

i
fx<0:

p
ass# n
eedt
oha
ndl
eneg
ati
vev
alu
es!

Al
ter
nat
iveex
ecu
tio
n(i
f-el
se)
:

Asecondf o
rmo fi
fst
atementi
sa l
ter
nat
iveexec
utio
n,inwhi
cht h
erear
etwo
pos
sib
ili
tiesandthec
ondit
iondet
ermi
neswhi
cho n
eg et
sexecut
ed.Thesyn
tax
lo
oksl i
ket hi
s:

Eg
:

i
fx%2 == 0:

p
rin
t'xi
sev
en'

el
se:
p
rin
t'xi
sodd'

I
ft her emai
nderwhenxi sdivi
dedb y2 is0,thenwek no
wt hatxisev en,andt h
e
p
rogram dis
playsamessag
et othateffec
t.Ifthecondi
tio
ni sfals
e,thes ec
onds etof
s
tatementsisexec
uted.Sinc
et hecon
diti
onmustbetrueorf al
se,exact
lyo neo fthe
a
lternat
iveswillbeexecut
ed.Thea l
tern
ati
vesar
ec all
edb ran
ches,b
ecauset h
eya re
b
ranchesint h
ef l
owo fexecut
ion.

Ch
ain
edc
ondi
tio
nal
s(i
f-el
if-el
se)
:

Somet
imesth
erearemor
et ha
nt wopo
ssib
ili
tiesan
dwen eedmor
et ha
nt wo
b
ran
ches.Onewa ytoex
pres
sac o
mp u
tati
onli
ket ha
ti sach
ain
edc o
ndi
tio
nal:

Eg
:

i
fx<y:

pri
nt'xi
sles
s
t
hany'eli
fx>y:

p
rin
t'xi
sgr
eat
ert
hany'

el
se:

p
rin
t'xa
ndya
reeq
ual
'

el
ifi sana b
brev
iati
ono
f“ el
sei
f.”Agai
n,exa
ctlyon
ebran
chwi
llbeexec
uted.Th
erei
s
nolimitonthen u
mberofeli
fsta
tement
s.Ifther
eisanels
ecl
aus
e,i
th a
st obeatth
e
end,buttheredoesn
thavetobeone.

Eg
:

i
fch
oice==
'
a':
dra
w_a
(
)
eli
fc hoi
ce
=='b'
:
dr
a w_b(
)el i
f
choic
e==' c'
:
draw_
c()

Eac
hc ondi
tionisch
ec kedinorder.Ifthefir
stisfa
lse,th
en extischec
ked,andsoon.
Ifoneoft hem i
strue,thecorr
espon
dingbran
chexec
utes,an
dt hesta
tementen
ds.Evenif
mor
et h
ano necondi
tionistru
e,o n
lyt h
ef i
rsttr
uebranc
hex ec
utes
.

3.
Exp
lai
nindet
aila
bou
tFr
uit
fulFu
nct
ion
s.

Ret
urnv
alu
es

So
meo
fth
ebu
ilt
-inf
unc
tio
nsweh
aveu
sed,s
ucha
sth
ema
thf
unc
tio
ns,p
rodu
ce
r
esu
lts
.Ca
lli
ngt
hef
unc
tio
ngen
era
tesav
alu
e,wh
ichweu
sua
llya
ssi
gnt
oav
ari
abl
e
o
rus
easp
arto
fanex
pres
sio
n.

Th
efi
rstex
amp
lei
sar
ea,wh
ichr
etu
rnst
hea
reao
fac
irc
lewi
tht
he
g
ivenr
adi
us:Eg
:

defa
rea
(ra
diu
s):

t
emp= ma
th.
pi*
r
adi
us*
*2r
etu
rnt
emp

Weh
aves
eent
her
etu
rns
tat
emen
tbef
ore,b
uti
naf
rui
tfu
lfu
nct
iont
her
etu
rn
s
tat
emen
tin
clu
desa
nex
pres
sio
n.Th
iss
tat
emen
tmea
ns:“
Ret
urni
mmedi
atel
yfr
om
t
hisf
unc
tio
nan
dus
eth
efo
llo
win
gex
pres
sio
nasar
etu
rnv
alu
e.”Th
eex
pres
sio
nca
n
b
ear
bit
rar
ilyc
omp
lic
ated,s
owec
oul
dha
vewr
itt
ent
hisf
unc
tio
nmo
rec
onc
isel
y:

defa
rea
(ra
diu
s):

r
etu
rnma
th.
pi*r
adi
us*
*2

Ont
heo
therh
and,t
emp
ora
ryv
ari
abl
esl
iket
empo
ftenma
kedeb
ugg
ingea
sier
.
So
met
imesi
tisu
sef
ult
oha
vemu
lti
pler
etu
rns
tat
emen
ts,o
nei
nea
chb
ran
cho
fa
c
ondi
tio
nal
:

def
a
bso
lut
e_v
alu
e(x
):
i
fx<0:

r
etu
rn-x

el
se:

r
etu
rnx

4.
Wri
teaPyt
honp
rog
ramt
ofi
ndt
hes
qua
rer
ooto
fan
umb
er.

n=i
nt(
inp
ut(
"En
teran
umb
ert
ofi
ndSq
uar
e
Roo
t:"
))
a
ppr
ox= 0.
5*n

b
ett
er= 0.
5*(
app
rox+ n
/ap
pro
x)

wh
ileb
ett
er!
=ap
pro
x:

a
ppr
ox= b
ett
er

b
ett
er= 0.
5*(
app
rox+ n
/ap
pro
x)

p
rin
t(a
ppr
ox)

5.Ex
pla
inRECURSI
ON.

Thep ro
ces
sinwh i
chaf unct
ionc al
lsits
elfdi rect
lyo rin
directl
yi sc al
led
rec
ursi
onandthec or
res
pondin
gf unct
ionisc a
lleda srecur
sivef u
nct
io n
.Using
rec
ursi
vealgo
rit
hm,cert
ainp r
oblemscanb esolvedq ui
teeasily.Examplesofs u
ch
pro
blemsareTowersofHan o
i( TOH),Inorder/Preor
der/Pos
torderTr eeTr a
vers
als
,
DFS ofGraph,etc
.

Pyt
honp
rog
ram:

#t
akei
npu
tfr
omt
heu
ser

num= i
nt(
inpu
t("En
teran
umb
er:
"
))deffact
(n):

i
fn==
1
:
r
etu
rn
n

el
se:

r
etu
rnn
*fa
ct(
n-1
)

p
rin
t(“
Fac
tor
ialo
fnn
umb
ersi
s:%d”%(
fac
t(n
)))

6.Ex
pla
ins
tri
ngs
lic
esa
nds
tri
ngi
mmu
tab
ili
ty.

St
rin
gsl
ices

Asegmen
tofas
tri
ngi
sca
lledas
lic
e.Sel
ect
ingas
lic
eiss
imi
lart
osel
ect
inga
c
hara
cter
:

>>>s='
Mon
tyPyt
hon
'

>>>p
rin
t
s
[0:
5]Mo
nty

>>>p
rin
ts[
6:1
2]

Theoper
ato
r[n
:m]
ret
urn
sth
epa
rto
fth
est
rin
gfr
omt
he“
n-et
h”c
har
act
ert
oth
e
“m-et
h”

c
har
act
er,in
cludi
ngt
hef
irs
tbu
tex
clu
din
gth
ela
st.I
fyo
uomi
tth
efi
rsti
ndex(
bef
ore
t
hecol
on),the

s
lic
es t
art
satth
ebeg
inn
ingo
fth
est
rin
g.I
fyo
uomi
tth
esec
ondi
ndex
,th
esl
iceg
oes
t
ot heendof

t
hes
tri
ng:

>>>f
rui
t= '
ban
ana
'
>>>f
rui
t[:
3]

b
an'

>>>f
rui
t[3:
]

a
na'

I
fth
efi
rsti
ndexi
sgr
eat
ert
hano
req
ualt
oth
esec
ondt
her
esu
lti
sanemp
tys
tri
ng,
r
epr
esen
tedb
ytwoq
uot
ati
onma
rks
:

>>>f
rui
t='
ban
ana
'

>>>f
rui
t[3:
3]

Anemp
tys
tri
ngc
ont
ain
snoc
har
act
ersa
ndh
asl
eng
th0,b
uto
thert
hant
hat
,iti
sth
e
s
amea
san
yot
hers
tri
ng.

St
rin
gimmu
tabi
lit
y.

Pyt
hons
tri
ngsa
rei
mmu
tab
le.ai
sno
tas
tri
ng.I
tisav
ari
abl
ewi
ths
tri
ngv
alu
e.Yo
u
c
antmu
tat
eth
est
rin
gbu
tca
nch
ang
ewh
atv
alu
eoft
hev
ari
abl
etoan
ews
tri
ng.

Eg
:

a= “
foo

#an
owp
oin
tst
o
f
oob
=a

#bn
owp
oin
tst
oth
esa
mef
oot
hata
p
oin
tst
oa=a
+a

#ap
oin
tst
oth
enews
tri
ng“
foo
foo
”,b
utbp
oin
tst
oth
esa
meo
ld“
foo

p
rin
t
a
p
rin
t
b

#
Ou
tpu
t
#f
oof
oo
#f
oo

I
tiso
bser
vedt
hatbh
asn
tch
ang
edev
ent
hou
ghah
asc
han
ged
t
hev
alu
e.7.Ex
pla
ins
tri
ngf
unc
tio
nsa
ndmet
hods
.

Th
erea
rean
umb
ero
fus
efu
lop
era
tio
nst
hatc
anb
eper
for
medwi
ths
tri
ng.On
eoft
he
mo
stu
sef
ulo
fth
esei
sth
efu
nct
ions
pli
t.Th
isf
unc
tio
nta
kesas
tri
ng(
typ
ica
llyal
ine
o
fin
putf
romt
heu
ser
)an
dsp
lit
siti
ntoi
ndi
vidu
alwo
rds
.

An
oth
eru
sef
ulf
unc
tio
nisl
ower
,wh
ichc
onv
ert
stex
tin
tol
owerc
ase.
Eg
:

>>>l
ine= i
npu
t(“
Wha
tisyo
urn
ame?”
)

Wh
ati
syo
urn
ame?Ti
mot
hyAl
anBu
dd

>>>l
own
ame= l
ine.
lower
()

>>>p
rin
tlo
wna
me.
spl
it(
)

[
timo
thy,a
lan
,bu
dd]

Ot
heru
sef
ulf
unc
tio
nswi
lls
ear
chas
tri
ngf
orag
ivent
extv
alu
e,o
rst
ripl
eadi
ngo
r
t
rai
lin
gwh
ites
pac
efr
om as
tri
ng.Ana
lter
nat
ivev
ers
iono
fsp
litt
akesa
sar
gumen
tth
e
s
epa
rat
ors
tri
ng.Th
est
rin
gisb
rok
eni
ntoal
istu
sin
gth
esep
ara
tora
sadi
vis
ion
.Th
is
c
anb
eus
efu
l,f
orex
amp
le,f
orb
rea
kin
gaf
ilep
athn
amei
ntop
art
s:

Eg
:

>>>p
ath
name= /
usr
/lo
cal
/bi
n/l
s

>>>p
ath
name.
spl
it(
/)

[
usr
,lo
cal
,bi
n,l
s]

Th
ein
ver
seo
fsp
liti
sth
efu
nct
ionj
oin
.Th
ear
gumen
ttoj
oini
sal
isto
fst
rin
gs.Th
e
v
alu
etot
hel
efto
fth
edo
tist
hes
epa
rat
ort
hatwi
llb
epl
acedb
etweenea
ch
el
emen
t.Of
tent
hisi
ssi
mpl
yanemp
tys
tri
ng.Th
eva
luesi
nth
eli
sta
rel
ami
nat
ed
a
lon
gwi
tht
hes
epa
rat
ort
opr
odu
cet
her
esu
lts
tri
ng.

>>>l
st= [
abc
,pdq
,xyz
]

>>>p
ri

n
t
:
:.
joi
n(l
st)
a
bc:
:pdq
::x
y
z

St
rin
gmet
hods

A met
hodi
ssi
mil
art
oaf
unc
tio
n—i
tta
kesa
rgu
men
tsa
ndr
etu
rnsav
alu
e—b
utt
he
s
ynt
axi
sdi
ffer
ent
.Fo
rex
amp
le,t
hemet
hodu
ppert
akesas
tri
nga
ndr
etu
rnsan
ew
s
tri
ngwi
tha
llu
pper
cas
elet
ter
s:

I
nst
eado
fth
efu
nct
ions
ynt
axu
pper
(wo
rd)
,itu
sest
hemet
hods
ynt
axwo
rd.
upp
er(
)

.
>>>wo
rd= '
ban
ana
'

>>>n
ew_
wor
d= wo
rd.
upp
er(
)

>>>p
rin
tnew_
wor
d
BANANA
Th
isf
ormo
fdo
tno
tat
ions
pec
ifi
est
hen
ameo
fth
emet
hod,u
pper
,an
dth
ena
meo
f
t
hes
tri
ngt
oap
plyt
hemet
hodt
o,wo
rd.Th
eemp
typ
aren
thes
esi
ndi
cat
eth
att
his
met
hodt
akesn
oar
gumen
t.A met
hodc
alli
sca
lleda
nin
voc
ati
on;i
nth
isc
ase,we
wo
ulds
ayt
hatwea
rei
nvo
kin
gup
pero
nth
ewo
rd.Asi
ttu
rnso
ut,t
her
eisas
tri
ng
met
hodn
amedf
indt
hati
srema
rka
blys
imi
lart
oth
efu
nct
ionwewr
ote:

>>>wo
rd= '
ban
ana
'

>>>i
ndex= wo
rd.
fi
nd(
'a'
)

>>>p
rin
tin
dex

I
nth
isex
amp
le,wei
nvo
kef
indo
nwo
rda
ndp
asst
hel
ett
erwea
rel
ook
ingf
ora
sa
p
ara
met
er.Ac
tua
lly,t
hef
indmet
hodi
smo
reg
ener
alt
hano
urf
unc
tio
n;i
tca
nfi
nd
s
ubs
tri
ngs
,no
tju
stc
har
act
ers
:

>>>wo
rd.
fi
nd(
'na
')

I
tca
nta
kea
sas
eco
nda
rgu
men
tth
ein
dexwh
erei
tsh
oul
dst
art
:

>>>wo
rd.
fi
nd(
'n'
,3)

4
An
dasat
hir
dar
gumen
tth
ein
dexwh
erei
tsh
oul
dst
op:

>>>n
ame='
bob
'

>>>n
ame.
fi
nd(
'b'
,1,2)

-1

Thi
ssear
chfai
lsb
eca
usebdo
esn
ota
ppea
rint
hei
ndexr
ang
efr
om 1t
o2 (
not
i
ncl
udi
ng2).

8.
Exp
lai
nst
rin
gmo
dul
e.

Th
est
rin
gmo
dul
eco
nta
insn
umb
ero
fus
efu
lco
nst
ant
san
dcl
ass
es,a
swel
lass
ome
dep
rec
atedl
ega
cyf
unc
tio
nst
hata
rea
lsoa
vai
lab
lea
smet
hodso
nst
rin
gs.

Eg
:

i
mpo
rts
tri
ng

t
ext= "
Mon
tyPyt
hon
'sFl
yin
g
Ci
rcu
s"p
rin
t"u
pper
","
=>"
,
s
tri
ng.
upp
er(
tex
t)p
rin
t"l
ower
",
"
=>"
,st
rin
g.l
ower
(tex
t)
p
rin
t"s
pli
t","
=>"
,st
rin
g.s
pli
t(t
ext
)

p
rin
t"j
oin
","
=>"
,st
rin
g.j
oin
(st
rin
g.s
pli
t(t
ext
),"
+")

p
rin
t"r
epl
ace"
,"=>"
,st
rin
g.r
epl
ace(
tex
t,"
Pyt
hon
","
Jav
a")

p
rin
t"f
ind"
,"=>"
,st
rin
g.f
ind(
tex
t,"
Pyt
hon
"),s
tri
ng.
fi
nd(
tex
t,
"
Jav
a")p
rin
t"c
oun
t","
=>"
,st
rin
g.c
oun
t(t
ext
,"n
")

Eg
:Us
ings
tri
ngmet
hodsi
nst
eado
fst
rin
gmo
dul
e
f
unc
tio
nst
ext= "
Mon
tyPyt
hon
'sFl
yin
gCi
rcu
s"

p
rin
t"u
pper
","
=>"
,
t
ext
.up
per
()p
rin
t"l
ower
",
"
=>"
,tex
t.l
ower
()p
rin
t
"
spl
it"
,"=>"
,tex
t.s
pli
t()

p
rin
t"j
oin
","
=>"
,"+"
.j
oin
(tex
t.s
pli
t()
)

p
rin
t"r
epl
ace"
,"=>"
,tex
t.r
epl
ace(
"Pyt
hon
",
"
Per
l")p
rin
t"f
ind"
,"=>"
,tex
t.f
ind(
"Pyt
hon
"),
t
ext
.fi
nd(
"Per
l")p
rin
t"c
oun
t","
=>"
,
t
ext
.co
unt
("n
")

9.
Exp
lai
nli
sta
sar
rays
.

1
0.Wr
iteaPyt
honp
rog
ramt
ofi
ndGCD o
ftwon
umb
ers
.
d1
=int
(inp
ut("Enteran u
mb er
:")
)
d2=i
nt(i
nput("En
t era
nother
nu
mber"
))r em=d1%d2

wh
ilerem!=0
:
prin
t(rem)
d1=d2
d2=r em
rem=d1%d2

p
rin
t("
gcdo
fgi
venn
umb
ersi
s:%d"%(
d2)
)

1
1.Wr
iteaPyt
honp
rog
ramt
ofi
ndt
heex
pon
ent
iat
iono
fan
umb
er.

pri
nt("
Calculati
ono fX^Y"
)
x=int
(inp
ut("EnterX Valu
e
:"
))y=i nt
(input("
Ent
erY
Value:"))po wered= x

i
fy== 0:
p
ower
ed=1

el
se:

wh
iley>1:
power
ed*
=
xy-= 1
p
rin
t(p
ower
ed)

1
2.Wr
iteaPyt
honp
rog
ramt
osu
mana
rra
yofn
umb
ers
.

defsu
m_arr
(
arr,
si
ze):i
f
(
size= = 0):

r
etu
rn0

el
se:

r
etu
rna
rr[
siz
e-1
]+s
um_
arr(
arr
,si
ze-1
)

n= i
nt(
inp
ut(
“En
tert
hen
umb
ero
fel
emen
tsf
or
t
heli
st:
”))a= []

f
orIi
nra
nge(
0,n
):

el
emen
t= in
t( i
npu
t(“
Ent
er
el
emen
t:”
))a.
app
pend(el
emen
t)

p
rin
t(“Theli
st
i
s:”)p
rin
ta

p
rin
t(“Th eSumis
:”)b=
s
um_ar
r(a
,n)pr
int
(b)

1
3.Wr
iteaPyt
honp
rog
ramt
oper
for
mli
nea
rsea
rch
.

da
ta= [
]

n= in
t(raw_
inp
ut(
'En
terNumberofEl
emen
tsi
nth
e
Ar
ray:')
)f oriinrang
e(0,n
) :
x= ra
w_i
nput
('EntertheEl
emen
t%d:
'
%(
i+1
))dat
a.app
en d(
x)

e= i
nt(
raw_
inpu
t('
Ent
ert
heEl
emen
ttob
e
Sear
ch'))pos= 0

f
oun
d= Fa
lse

wh
ilep o
s<na ndnot
found:if
int
(data[
pos
])==e:

fou
nd=
Tr
ueels
e:

po
s=
p
os+1iff
oun
d:

pr
int(
'Element%dFo
unda
tPo
sit
ion%d'
%(
e,po
s+1))else:

p
rin
t('
Elemen
t%di
sNo
tFo
undi
nth
eAr
ray'
%(e)
)

1
4.Wr
iteaPyt
honp
rog
ramt
oper
for
mbi
nar
ysea
rch
.

da
ta= [
]

n= in
t(i
npu
t('
EnterNumbero
fElemen
tsi
nthe
Ar
ray:')
)prin
t('
Enterth
eElemen
tsinAs
cen
din
g
Or
der')

f
orii
nra
nge(
0,n
):

x= in
t(inp
ut('
Entert
heEl
emen
t%d:
'
%(
i+1
)))da
ta.a
ppend(x)
e= i
nt(
input
('Entert
heEl
emen
ttob
e
Sear
ch' )
)f irs
t= 0

la
st= n
-1
fou
nd=
Fals
e

wh
ile(firs
t<=l
astan
dn o
t
foun
d):mid= (fi
rst+
las
t)/2

i
fi n
t(da
ta[
mid]
)
== e:found=
Tr
ue

el
se:

i
fe<
i
nt(
dat
a[mi
d])
:
l
ast= mid- 1

el
se:

f
irs
t= mi
d
+ 1i
ff ou
nd:

p
r i
nt(
'El
emen
t%dFo
unda
tPo
sit
ion%d'
%(e,
mid+1
))els
e:

p
rin
t('
Elemen
t%di
sNo
tFo
undi
nth
eAr
ray'
%(e)
)

UNI
TIV
LI
STS,TUPLES AND DI
CTI
ONARI
ES

PART- A (
2 Ma
rks
)

1
.Wh
ati
sal
ist
?

Alistisanorder
eds etofval
ues
,whereeac
hv al
ueisiden
tifi
edb yanindex.The
v
aluestha
tmak eupal is
tarecall
editsel
ements
.Lis
tsaresimil
artost
rings
,whicha
re
o
rderedsetso
fc har
acter
s,ex
cepttha
ttheelementso
fal is
tc anhav
eanyt ype.

2.So
lvea
)[0]*4 a
ndb)[
1,2,3]*3.

>>> [
0]*4 [
0,0,0,0]

>>>[
1,2,3]*3[
1,2,3,1
,2,3,1
,2,3]

3.
Letl
ist= [
a,b,c
,d,e,f
].Fi
nda
)li
st[
1:
3]b)t
[:4]c
)t[
3:].

>>>l
ist= [
a,b
,c,d,e,f
]

>>>l
ist
[1:
3][
b,c
]

>>>l
ist
[:4][
a,b
,c,d]

>>>l
ist
[3:
][d,e,f
]

4.Men
tio
nan
y5l
istmet
hods
.

a
ppen
d(),
ext
end(
),s
ort
(),p
op(
),i
ndex
(),
in
ser
tan
dremo
ve(
)

5.St
atet
hedi
ffer
enc
ebet
weenl
ist
san
ddi
cti
ona
ry.

Li
stisamutabl
et ypemean
ingtha
ti tcanb
emo di
fiedwherea
sdi c
tion
aryisimmu
table
an
disak eyvaluestor
e.Di
cti
ona
ryi sno
torder
eda nditrequi
resthatthekeysare
ha
sha
blewher
easlistcanst
oreas eq
uen
ceofo b
ject
si nacertai
no r
der.

6.Wh
ati
sLi
stmu
tabi
lit
yinPyt
hon
?Gi
vea
nex
amp
le.
Pythonrepresent
sa llit
sda taaso b
j ec
ts.Someo ftheseobjectsli
kel i
stsand
dict
ion
ariesar emutabl
e,i.e.
,thei
rc ont
entc a
nb ec h
angedwi t
houtcha
n g
ingtheir
iden
tit
y.Ot hero bj
ectslik
ei nt
egers,floa
ts,str
ing
sa ndtup
lesa reobjectst
hatc an
notb
e
chan
ged.

Ex
amp
le:

>>>n
umb
ers= [
17,1
23]

>>>n
umb
ers
[1
]= 5

>>>p
rin
tnu
mber
s[1
7,5]

7.Wh
ati
sal
ias
ingi
nli
st?Gi
vea
nex
amp
le.

Anobj
ectwithmoret h
anonereferenc
ehasmo
r eth
anonena
me,th
ent
heobj
ectis
s
aidtobealia
sed.Exa
mp l far
e:I eferstoa
nobjectandwea
ssig
nb= a
,th
enb o
th
v
ari
abl
esref
ert othesameob
ject
:

>>>a= [
1,2,3]

>>>b= a

>>>bi
saTr
ue

8.Def
inec
lon
ingi
nli
st.

Inordertomodif
yal i
stan
da l
sok eepac o
pyoftheo
rig
ina
l,i
tisrequ
iredtoma
ke
aco
pyo ft
h elis
tits
elf
,no
tj u
sttheref
erence.Th
isp
roc
essi
scall
edclo
nin
g,toavo
idthe
a
mbi
gui
tyoft h
ewo r
d


cop
y”.
9.Ex
pla
inLi
stp
ara
met
erswi
tha
nex
amp
le.

Pa
ssin
gal is
ta sana r
gumen
ta ct
ual
lyp a
ssesaref
eren
cetothelis
t,notac o
py
o
fthel i
st.Forex a
mple,thefunc
tio
nh ea
dt akesali
stasanar
gumen
ta n
dr et
urns
t
hefir
stel ement
:

def
h
ead(li
st)
:
r
etu
rnl i
st[
0]
o
utpu
t:

>>>n
umb
ers= [
1,2,3]

>>>h
ead(
numb
ers
)

1
0.Wr
iteap ro
gra
mi nPyth
ont odel
etef i
rstel
emen
tfr
om
ali
st.defdelet
eHea
d(li
st)
:dellis
t[0]

Her
esh
owdel
eteHea
disu
sed:

>>>n
umb
ers= [
1,2,3]

>>>del
eteHea
d(n
umb
ers
)

>>>p
rin
tnu
mber
s[2,3]

1
1.Wr
iteaprogr
ami
nPyt
honr
etu
rnsal
istt
hatc
ont
ain
sal
lbu
tth
efi
rstel
emen
tof
t
hegiv
enli
st.

def
tai
l(li
st)
:
retur
n
lis
t[1
:]

Her
esh
owt
aili
sus
ed:

>>>n
umb
ers= [
1,2,3]

>>>r
est= t
ail
(nu
mber
s)
>>>p
rin
tres
t[2,3]
1
2.Wh
ati
sth
eben
efi
tofu
sin
gtu
plea
ssi
gnmen
tinPyt
hon
?

I
tisoftenus
efult
oswapt
heval
uesoftwovar
iab
les.Wi
thcon
vent
ion
ala
ssi
gnmen
tsa
t
emp
ora
ryv a
riab
lewou
ldbeus
ed.Forex
ampl
e,tos wa
paa n
db :

>>>t
emp= a

>>>a= b

>>>b= t
emp

Th
iss
olu
tio
nisc
umb
ers
ome;t
upl
eas
sig
nmen
tismo
reel
ega
nt:

>>>a
,b= b
,a

1
3.Def
inekey-v
alu
epa
irs
.

Theelemen
tsofadict
ionaryapp
earinac o
mma
-separ
a t
edl i
st.Eac
hentr
yc on
tai
nsan
i
ndexandav al
ues
eparat
edb yac ol
on.Inadic
tio
nary,th
ei ndi
cesar
ec al
ledkeys
,so
th
eelementsa
reca
lledk ey-v
aluepai
rs.

1
4.Def
inedi
cti
ona
rywi
tha
nex
amp
le.

A di
cti
ona
ryisa na s
soci
ati
vea rr
ay(als
ok no
wna shas
hes).Anykeyofthedi
cti
ona
ryi s
a
ssoc
iat
ed( o
rma pped)toav a
lue.Theval
uesofadi cti
onaryca
nb ean
yPythondata
t
ype.Sodicti
ona
riesa r
eu no
rderedkey-va
lue-p
airs
.
Ex
amp
le:

>>>en
g2s
p= {
} # emp
tydi
cti
ona
ry

>>>en
g2s
p[o
ne]= u
no

>>>en
g2s
p[t
wo]= do
s

1
5.Ho
wtor
etu
rnt
upl
esa
sva
lues
?
Afun
ctioncanonl
yretur
no nevalu
e,butifth
evalu
ei satupl
e,th
eef fec
tisthes a
me
a
sretur
ningmul
tip
levalues
.Forexample,i
fwewanttodivi
detwoint
egersan
dc ompute
t
hequoti
entandremai
nder,iti
si n
effi
cien
ttoco
mputex/
ya ndth
enx %y.Itisb
et t
ert o
c
ompu
tet hembot
ha tthesametime.
>>>t= di
vmo
d(7,3)

>>>p
rin
tt(
2,1
)

1
6.Li
stt
wodi
cti
ona
ryo
per
ati
ons
.

 Del-r
emo
vesk
ey-v
alu
epa
irsf
rom adi
cti
ona
ry

 Len- r
etu
rnst
hen
umb
ero
fkey-v
alu
epa
irs

1
7.Def
inedi
cti
ona
rymet
hodswi
tha
nex
amp
le.

A methodissimila
rt oaf u
nct
ion—ittakesarg
u ment
sa ndretur
nsav a
lue— bu
tt h
esynt
ax
isdif
feren
t.Fo rexampl
e,thek eysmet
ho dtakesadi cti
onar
ya ndretu
rnsalistoft
he
keysthatappear,butin
steadoft hefu
nc t
ionsynta
xk eys(
eng2sp)
,methodsyn
tax
eng2s
p.k
eys()isu s
ed.
>>>en
g2s
p.k
eys
()[
one,t
hree,t
wo]

1
8.Def
ineLi
stCo
mpr
ehen
sio
n.

Li
stcomp
rehensi
onsapp
lya nar
bit
rar
yex pres
sio
ntoitemsi
na niter
ablerat
hertha
n
ap
plyi
ngfun
c t
ion.Itpr
ovi
desac o
mpactwayo fmapp
ingalis
ti n
toa n
otherli
stb
y
ap
plyi
ngaf unc
tiontoeac
ho ftheelemen
tso ftheli
st.

1
9.Wr
iteaPyt ho
npr
ogr
amt
oswa
ptwo
va
ria
bles
.x= 5

y= 1
0
t
emp=
xx=
y
y= t
emp
p
rint
('Thevalu
eo fxa f
terswa
ppi
ng:
{
}.
for
ma t
(x)
)p ri
nt(
'Theval
ueofya f
ter
s
wapping
:{}.
for
mat(y)
)

20.
Wri
tet
hes
ynt
axf
orl
istc
omp
reh
ens
ion
.

Theli
stcomp
rehens
ions
tar
tswit
ha'['an
d' ]'
,tohelpusr
emembert
hattheres
ulti
s
go
ingtob
eal i
st.Thebas
icsyn
taxi
s[expr
essi
onf
o rit
eminlis
tifcon
dit
ion
al].

PART B (
16MARKS)

1
. Ex
pla
ini
ndet
aila
bou
tli
sts
,li
sto
per
ati
onsa
ndl
ists
lic
es.

Al i
stisanorderedsetofvalues,whereea c
hv alu
ei siden
tif
iedb yanindex.Th eva
luestha
t
makeupal i
sta r
ec a
lledit
sel ement
s .Lis
tsa r
es i
milartostr
ings
,whic
ha reo r
deredsetsof
ch
aract
ers
,exceptthattheelementsofal i
stc anhaveanytype.Ther
ea reseveralwaysto
cr
eatean ewlis
t.Thes i
mpl
esti stoen cl
oset h
eel ement
sinsquarebr
ackets([and]
):

[
10,20,30,40]

[
"sp
am"
,"b
ung
ee"
,"s
wal
low"
]

Th
efo
llo
win
gli
stc
ont
ain
sas
tri
ng,af
loa
t,a
nin
teg
er,a
nd(
mir
abi
ledi
ctu
)an
oth
erl
ist
:

[
"hel
lo"
,2.
0,5,[
10,20]
]

Alis
twithi
nan
oth
erl i
stiss
aidtobenes
ted.Lis
tstha
tco
nta
inc
ons
ecu
tiv
ein
teg
ersa
re
c
ommon,s
oPyth
onp r
ovi
desasimp
lewaytocreat
et h
em:

>>>r
ang
e(1
,
5)[
1,2,3,4]
.
LI
ST OPERATI
ONS

Th
e+ o
per
ato
rco
nca
ten
atesl
ist
s

:>>>a= [
1,2,3]

>>>b= [
4,5,6]

>>>c= a+ b

>>>p
rin
tc[
1,2,3,4,5,6]

Si
mil
arl
y,t
he*o
per
ato
rrep
eat
sal
istag
ivenn
umb
ero
fti
mes
:

>>>[
0]*4 [
0,0,0,0]

>>>[
1,2,3]*3[
1,2,3,1
,2,3,1
,2,3]

LI
ST SLI
CES

Th
esl
iceo
per
ato
ral
sowo
rkso
nli
sts
:

>>>t= [
'a'
,'b
','
c'
,d,'
e'
,'f
']

>>>t
[1:
3][
'b'
,'c
']

>>>t
[:4][
'a'
,'b
','
c'
,'d'
]

>>>t
[3:
]['
d','
e'
,'f
']
I
fweo mi
tthefi
rsti
ndex
,t h
eslic
estar
tsa tt
heb
egi
nni
ng.I
fweo mi
tt hes
eco
nd,t
hes
lic
e
g
oest
ot heen
d.Soifweo mitb
oth,t
hes l
icei
sacop
yo fthewh
olelis
t.

>>>t
[:][
'a'
,'b
','
c'
,'d'
,'e'
,'f
']

Sin
cel i
stsaremutabl
e,itisoft
enu s
efu
lt omak
eac o
pyb ef
orep
erf
ormi
ngo p
era
tio
nstha
t
fo
ld,spi
ndleo rmuti
lateli
sts
.A sl
iceoper
ato
ronth
el ef
ts i
deofanass
ign
mentcanup
date
mul
tip
leel emen
ts:

>>>t= [
'a'
,'b
','
c'
,d,'
e'
,'f
']

>>>t
[1:
3]= [
'x'
,'y'
]

>>>p
rin
tt[
'a'
,'x
','
y','
d','
e'
,'f
,]

Li
ke s
tri
ngs
,li
stsc
anb
ein
dex
eda
nds
lic
ed:

>>>l
ist= [
2,4,"
usu
rp"
,9.
0,"
n"]

>>>l
ist
[2]

u
sur
p'

>>>
lis
t[3:
]
[9.
0,n']

Muchl
ikethes
lic
eofastr
ingisasu
bst
rin
g,t
hesli
ceofali
stisal
ist
.Ho
wev
er,l
ist
sdi
ffer
fr
omstr
ing
sintha
tweca
na ss
ignn
ewval
uestoth
ei t
emsi
nalis
t:
>>>l
ist
[1]= 1
7

>>>l
ist

[
2,1
7,u
sur
p',9.
0,n
']

Wec
ana
ssi
gnn
ewv
alu
est
osl
iceso
fth
eli
sts
,wh
ichdo
n'tev
enh
avet
obet
hes
amel
eng
th:

>>>l
ist
[1:
4]= [
"op
por
tun
ist
ic"
,"el
k"]

>>>l
ist

[
2,o
ppo
rtu
nis
tic
',el
k',n
']

I
t'sev
enp
oss
ibl
etoa
ppen
dit
emso
ntot
hes
tar
tofl
ist
sbya
ssi
gni
ngt
oanemp
tys
lic
e:

>>>l
ist
[:0]= [
3.1
4,2.
71]

>>>l
ist

[
3.1
4,2.
71,2,o
ppo
rtu
nis
tic
',el
k',n
']

Si
mil
arl
y,yo
uca
nap
pen
dtot
heen
doft
hel
istb
ysp
eci
fyi
nga
nemp
tys
lic
eaf
tert
heen
d:

>>>l
ist
[len
(li
st)
:]= [
fou
r',s
cor
e']

>>>l
ist
[
3.1
4,2.
71,2,o
ppo
rtu
nis
tic
',el
k',n
',f
our
',s
cor
e']

Yo
uca
nal
soc
omp
let
elyc
han
get
hec
ont
ent
sofal
ist
:

>>>l
ist
[:]= [
new'
,li
st'
,co
nten
ts'
]

>>>l
ist

[
new'
,li
st'
,co
nten
ts'
]

Th
eri
ght
-ha
nds
ideo
fal
ista
ssi
gnmen
tst
atemen
tca
nbea
nyi
ter
abl
etyp
e:

>>>l
ist
[:2]= (
elemen
t',
(t'
,
),[
])

>>>l
ist

[
elemen
t',(
t',
),[
],c
ont
ent
s']

Wi
ths
lic
ingyo
uca
ncr
eat
eco
pyo
fli
sts
inc
esl
icer
etu
rnsan
ewl
ist
:

>>>o
rig
ina
l= [
1,el
emen
t',[
]]

>>>l
ist
_co
py= o
rig
ina
l[:
]
>>>l
ist
_co
py

[
1,el
emen
t',[
]]

>>>l
ist
_co
py.
app
end(
newel
emen
t')

>>>l
ist
_co
py

[
1,el
emen
t',[
],n
ewel
emen
t']

>>>ori
gin
al
[1
,el
ement'
,
[]
]

Note,ho
wev
er,th
atthisi
sas h
all
owc op
yan
dco
nta
insr
efer
enc
est
oel
emen
tsf
romt
heo
rig
ina
l
li
st,sobecar
efulwi
thmuta
bletypes
:

>>>l
ist
_co
py[
2].
app
end(
somet
hin
g')

>>>o
rig
ina
l

[
1,el
emen
t',[
somet
hin
g']
]

No
n-Co
nti
nuo
uss
lic
es

I
tisa l
sopo
ssi
bletogetno
n-co
ntin
uouspa
rtsofa na
rra
y.Ifon
ewant
edtogetev
eryn
-th
o
ccur
renc
eofal i
st,o
newouldus
et he::oper
ator
.Thesyn
taxi
sa:
b:nwh
ereaandbarethe
s
tar
ta n
dendo fthesli
cet
ob eopera
tedupon.

>>>lis
t= [if
orii
n
ran
ge(
10)]
>>>l
ist

[
0,1
,2,3,4,5,6,7,8,9]

>>>li
st[
::
2
][0,2,4,
6,8]

>>>li
st[
1:
7:2
][1
,3,5]

2. Ex
pla
ini
ndet
aila
bou
tli
stmet
hodsa
ndl
istl
oop
swi
thex
amp
les
.

Pyt
honp
rov
idesmet
hodst
hato
per
ateo
nli
sts
.So
meo
fth
emet
hodsa
re

 Ap
pen
d()

 Ex
ten
d()

 So
rt(
)

 Po
p()

Fo
rex
amp
le,a
ppen
daddsan
ewel
emen
ttot
heen
dofal
ist
:

>>>t= [
'a'
,'b
','
c'
]
>>>t
.ap
pen
d('
d')

>>>p
rin
tt[
'a'
,'b
','
c'
,'d'
]

Ex
ten
dta
kesal
ista
sana
rgu
men
tan
dap
pen
dsa
llo
fth
eel
emen
ts:

>>>t
1= [
'a'
,'b
','
c'
]

>>>t
2= [
'd'
,'e'
]

>>>t
1.
ext
end(
t2)

>>>p
rin
tt1[
'a'
,'b
','
c'
,'d'
,'e'
]

Th
isex
amp
lel
eav
est
2un
modi
fied.s
orta
rra
ngest
heel
emen
tso
fth
eli
stf
roml
owt
ohi
gh:

>>>t= [
'd'
,'c
','
e'
,'b
','
a'
]

>>>t
.s
ort
()

>>>p
rin
tt[
'a'
,'b
','
c'
,'d'
,'e'
]

Remo
vethei
temint
hel i
statt
hei
ndexia
ndr
etu
rni
t fii
.I sno
tgi
ven
,remo
vet
het
hel
ast
it
em i
nth
elista
ndret
urnit
.

>>>l
ist= [
1,2,3,4]

>>>a= l
ist
.po
p(0)
>>>l
is

t[
2,

3,4]

>>>a

Li
stmet
hodsa
rea
llv
oid;t
heymo
dif
yth
eli
sta
ndr
etu
rnNo
ne.

LI
ST LOOPS

Herear
etwof
unct
ion
st ha
tbo
thg
ener
atet
enmi
lli
onr
ando
mnu
mber
s,a
ndr
etu
rnt
hes
umo
fth
e
nu
mber
s.Th
eybot
hwo rk
.

i
mpo
rtr
ando
m

j
oe= r
ando
m.Ra
ndo
m()

defs
um1
():

"
""Bu
ildal
isto
fra
ndo
mnu
mber
s,t
hens
umt
hem "
""# Gen
era
teo
ner
ando
m˓→n
umb
er

x
s= [
]

f
orii
nra
nge(
10000000)
:

n
um= j
oe.
ran
dra
nge(
1000 )

x
s.a
ppen
d(n
um) # Sa
vei
tino
url
ist

t
ot= s
um(
xs)
r
etu
rnt
ot

defs
um2(
):

"
""Su
mth
era
ndo
mnu
mber
sasweg
ener
atet
hem "
""

t
ot= 0

f
orii
nra
nge(
10000000)
:

n
um= j
oe.
ran
dra
nge(
1000)

t
ot+= n
um

r
etu
rnt
ot

p
rin
t(s
um1
())

p
rin
t(s
um2(
))

3. Ex
pla
ini
ndet
aila
bou
tmu
tab
ili
tya
ndt
upl
eswi
thaPyt
honp
rog
ram.

MUTABI
LITY

Unli
kestr
ing
s,li
stsar
emutab
le,whi
chmea n
swecanch
angethei
relement
s.Usi
ngt
heb
rac
ket
op
erato
ront helefts
ideo
fa nass
ignmen
t,weca
nupdat
eo n
eo fth
eel emen
ts:

>>>f
rui
t= [
"ba
nan
a","
app
le"
,"q
uin
ce"
]

>>>f
rui
t[0]= "
pea
r"

>>>f
rui
t[-1
]= "
ora
nge"

>>>p
rin
tfr
uit[
pea
r,a
ppl
e,o
ran
ge]

Wi
tht
hes
lic
eop
era
torwec
anu
pda
tes
ever
alel
emen
tsa
ton
ce:
>>>l
ist= [
a,b
,c,d,e,f
]

>>>l
ist
[1:
3]= [
x,y]

>>>p
rin
tli
st[
a,x
,y,d,e,f
]\

Wec
ana
lsor
emo
veel
emen
tsf
rom al
istb
yas
sig
nin
gth
eemp
tyl
istt
oth
em:

>>>l
ist= [
a,b
,c,d,e,f
]

>>>l
ist
[1:
3]= [
]

>>>p
rin
tli
st[
a,d,e,f
]

Andwec a
naddel
emen
tst
oal
istb
ysq
ueez
ingt
hem i
ntoa
nemp
tys
lic
eatt
hedes
ired
lo
cat
ion
:

>>>l
ist= [
a,d,f
]

>>>l
ist
[1:
1]= [
b,c
]

>>>p
rin
tli
st[
a,b
,c,d,f
]

>>>l
ist
[4:
4]= [
e]

>>>p
rin
tli
st[
a,b
,c,d,e,f
]
Tu
plea
ssi
gnmen
t

I
tisof
tenus
efult
oswaptheval
uesoftwov
ari
abl
es.Wi
thco
nven
tio
nala
ssi
gnmen
ts,yo
uha
ve
t
ouseatemp
ora
ryvar
iab
le.Fo
rex a
mpl
e,tos
wapaa ndb:

>>>t
emp= a

>>>a= b

>>>b= t
emp

Th
iss
olu
tio
nisc
umb
ers
ome;t
upl
eas
sig
nmen
tismo
reel
ega
nt:

>>>a
,b= b
,a

Thel ef
ts i
deisat u
pleofv ar
iabl
es;t
her i
ghtsideisatupl
eo fex
press
ion
s.Eachval
ueis
as
sig
nedt oitsrespec
tiv
ev ar
iabl
e.Alltheexpres
sio
nsontherig
htsi
dea reeval
uatedbef
ore
anyoft heass
ignment
s.Then u
mbero fv
ari
ablesonthelef
ta ndthenumb
ero fval
uesonthe
ri
ghth a
vet obet hesame:

>>>a
,b= 1
,2,3

ValueErro
r:toomanyv a
luestoun
pac
kMo r
eg ener
ally,th
erigh
tsidec a
nb ea
nyk i
ndof
sequ
en c
e( st
rin
g,li
stort up
le)
.Forexa
mple,tospl
ita nema
iladdres
sintoausern
ameanda
domain,youcouldwri
te:

>>>a
ddr= '
mon
ty@p
yth
on.
org
'
>>>u
name,do
mai
n= a
ddr
.s
pli
t('
@')

Theret
urnv
alu
ef romsp
liti
sal
istwi
tht
woel
emen
ts;t
hef
irs
tel
emen
tisa
ssi
gnedt
oun
ame,
th
esecondt
odo ma
in.

>>>p
rin
tun
amemo
nty

>>>p
rin
tdo
mai
npyt
hon
.or
g

4. Wh
ati
stu
plea
ssi
gnmen
t?Ex
pla
ini
twi
tha
nex
amp
le.

I
tisof
tenus
efult
oswaptheval
uesoftwov
ari
abl
es.Wi
thco
nven
tio
nala
ssi
gnmen
ts,yo
uha
ve
t
ouseatemp
ora
ryvar
iab
le.Fo
rex a
mpl
e,tos
wapaa ndb:

>>>t
emp= a

>>>a= b

>>>b= t
emp

Th
iss
olu
tio
nisc
umb
ers
ome;t
upl
eas
sig
nmen
tismo
reel
ega
nt:

>>>a
,b= b
,a

Thel ef
ts i
deisat u
pleofv ar
iabl
es;t
her i
ghtsideisatupl
eo fex
press
ion
s.Eachval
ueis
as
sig
nedt oitsrespec
tiv
ev ar
iabl
e.Alltheexpres
sio
nsontherig
htsi
dea reeval
uatedbef
ore
anyoft heass
ignment
s.Then u
mbero fv
ari
ablesonthelef
ta ndthenumb
ero fval
uesonthe
ri
ghth a
vet obet hesame:
>>>a
,b= 1
,2,3

ValueErro
r:toomanyv a
luestoun
pac
kMo r
eg ener
ally,th
erigh
tsidec a
nb ea
nyk i
ndof
sequ
en c
e( st
rin
g,li
stort up
le)
.Forexa
mple,tospl
ita nema
iladdres
sintoausern
ameanda
domain,youcouldwri
te:

>>>a
ddr= '
mon
ty@p
yth
on.
org
'

>>>u
name,do
mai
n= a
ddr
.s
pli
t('
@')

Theret
urnv
alu
ef romsp
liti
sal
istwi
tht
woel
emen
ts;t
hef
irs
tel
emen
tisa
ssi
gnedt
oun
ame,
th
esecondt
odo ma
in.

>>>p
rin
tun
amemo
nty

>>>p
rin
tdo
mai
npyt
hon
.or
g

5. I
sitp
oss
ibl
etor
etu
rnt
upl
easv
alu
es?Ju
sti
fyyo
ura
nswerwi
tha
nex
amp
le.

Yes,i
tispos
sibl
et or
etu
rnt u
pleasv
alu
es.Ex
ample:Func
tio
nscanretur
ntu
plesa
sret
urn
va
lues
.Forexampl
e,wecoul
dwr i
teafun
cti
ontha
ts wap
st wopa
rameter
s:

defs
wap
(x,y)
:

r
etu
rny,x
Th
enwec
ana
ssi
gnt
her
etu
rnv
alu
etoat
upl
ewi
tht
wov
ari
abl
es:

a
,b= s
wap
(a,b
)

I
nthi
sc a
se,t
hereisnogr
eatadva
ntag
ei nmaki
ngswapafunc
tion.Infa
ct,t
her
eisada
nger
i
ntr
yingtoenca
psu
lat
eswap,wh
ichisthefol
lowi
ngtemp
tin
gmi s
take:

defs
wap
(x,y)
:# i
nco
rrec
tver
sio
n

x
,y= y,x

Ifwec al
lt hi
sf un
cti
onli
ket h
is:swa
p(a,b)thenaa ndxarea li
asesforthes a
mev a
lue.
Chan
gin
gxi n
sideswapmakesxr ef
ertoadi ff
erentval
ue,b
uti thasn oeffec
to nainma i
n.
Simi
lar
ly,changi
ngyh asnoeffectonb.Thisfunc
tio
nr u
nswit
houtp r
oducin
ga nerr
ormessag
e,
butitdoesn
tdowh atweint
ended.Thisisanexampl
eo fasemanti
cer ro
r.

Thebui
lt-i
nfunc
tiondiv
modtak
est woarg
ument
sandr
etu
rnsat
upl
eoft
wov
alu
es,t
he
qu
oti
entandremai
nder
.Yo uc
ansto
ret h
er es
ultasat
upl
e:

>>>t= di
vmo
d(7,3)

>>>p
rin
tt(
2,1
)

Oru
set
upl
eas
sig
nmen
ttos
tor
eth
eel
emen
tss
epa
rat
ely:

>>>q
uot
,rem= di
vmo
d(7,3)

>>>p
rin
tqu
ot2
>>>p
rin
trem1

Herei
sanexampl
eo faf u
ncti
onth
atr et
urn
sat u
ple:defmin_max(
t):r
etur
nmin
(t)
,max(
t)
maxandmina
reb ui
lt-i
nfunc
tio
nstha
tf i
ndt h
elargestands
ma l
les
telemen
tso
fas eq
uence.
min
_ma
xc o
mpu
tesbothandretur
nsatupleoftwovalues.

6. Ex
pla
ini
ndet
aila
bou
tdi
cti
ona
riesa
ndi
tso
per
ati
ons
.

DI
CTI
ONARI
ES

A dictio
naryisli
k ealis
t,butmoreg ener
al.Inal is
t,theindi
cesha v
et obeinteger
s;ina
di
ct i
onarytheycanb e(al
most)anytype.Yo ucanthinkofadi ct
ion
a r
ya sama p
p i
ngb et
ween
aseto fin
dices(whi
charec al
ledkeys)a ndas etofv a
lues
.Eachk eyma p
stoav al
ue.The
as
sociati
ono fakeya ndav al
ueiscal l
edak ey-v
aluepairorsometi
mesa nit
em.Asa n
example,wellbui
ldadi c
tion
arythatma psfrom En
glis
ht oSpani
shwo rds
,sothek eysandthe
va
luesa reallstr
ings
.

Thefun
cti
ondic
tc rea
tesanewdict
iona
rywit
hn oi
tems
.Bec
aus
edi
cti
sth
ena
meo
fab
uil
t-
i
nf u
nct
ion
,yo
us ho
ulda v
oidus
ingi
ta savar
iabl
ename.

>>>en
g2s
p= di
ct(
)
>>>p
rin
ten
g2s
p{}

Thesqui
ggly-br
ackets
,{},rep
resentanemp t
ydicti
ona
ry.Toa ddi temst
ot hedict
ion
ary,you
canus
es quar
eb r
ackets
:>>>en g2s
p['
one'
]= 'u
no'Thisli
nec rea
tesa ni
tem thatmap
sf ro
mt he
key'o
ne'tot hevalue'uno
'.Ifwep ri
ntt h
edicti
onar
ya ga
in,wes eeak ey-va
luepairwitha
col
onbetweenthek eyandv alu
e:

>>>p
rin
ten
g2s
p{o
ne'
:'u
no'
}

Thiso
utputfo
rma
tisa
lsoa
nin
putf
orma
t.Fo
rex
amp
le,yo
uca
ncr
eat
ean
ewdi
cti
ona
rywi
th
th
reeitems
:

>>> en
g2s
p= {
one'
:'u
no'
,'t
wo'
:'do
s',

'
thr
ee'
:'t
res
'}Bu
tifyo
upr
inten
g2s
p,

yo
umi
ghtb
esu
rpr
ised:

>>>p
rin
ten
g2s
p{o
ne'
:'u
no'
,'t
hree'
:'t
res
','
two
':'
dos
'}

Theo r
dero fthek ey-val
u epair
sisn otthesame.Infact,i
fyoutypethesameexampleon
yourcomp
uter,youmi g
htg etadi fferentresul
t.Ingen
er a
l,theo
rderofitemsinadictio
nary
isunp
redic
table.Butt h
atsn otap r
o b
l em b
ecauseth
eel emen
tsofadict
ionaryarenev
er
in
dexedwithi nt
egerindices.In
stea
d,yo uusethekeyst oloo
kupthecorr
espon
dingval
ues:

>>>p
rin
ten
g2s
p['
two
']'
dos
'

Thekey'
two
'al
waysmapstoth
ev a
lue'dos's
otheo
rdero
fth
eit
emsdo
esn
tma
tter
.Ift
he
keyi
snti
nthedic
tio
nar
y,yougetanex
c ep
tio
n:

>>>p
rin
ten
g2s
p['
fou
r']KeyEr
ror
:'f
our
'
Th
elenf
unc
tio
nwo
rkso
ndi
cti
ona
ries
;itr
etu
rnst
hen
umb
ero
fkey-v
alu
epa
irs
:

>>>l
en(
eng
2sp
)

Theinoper
ato
rwo r
kso
ndi
cti
ona
ries
;ittel
lsyouwhet
hers
omet
hin
gap
pea
rsa
sak
eyi
nth
e
di
cti
ona
ry(appea
rin
gasav
alu
ei snotgo
odenou
gh).

>>>o
ne'i
nen
g2s
pTr
ue

>>>u
no'i
nen
g2s
pFa
lse

Toseewhetherso
methi
ngap
pea
rsasaval
uei
nadic
tio
na r
y,youca
nus
eth
emet
hodv
alu
es,
wh
ichret
urn
st heval
uesasali
st,a
ndt
henus
eth
eino perat
or:

>>>v
als= en
g2s
p.v
alu
es(
)

>>>u
no'i
nva
ls

Tr
ue
Theino per
atorusesdi fferenta
lgor
ithmsfo
rl i
stsa nddiction
ari
es.Forlist
s,itusesas earc
h
al
gori
thm,asinSec t
ion8. 6.Asthelistget
sl on
ger,thes earc
ht i
meg etslong
erindi rect
pr
opor
tion
.Fo rdiction
aries,Pyth
onu s
esa nalg
orith
mc a
lledah a
shta
blet h
ath asar emar
kable
pr
opert
y:t heino perat
ort a
kesabo
utt hesa
mea mo u
nto ft i
men omatterhowma nyitemsthere
ar
ei nadi cti
ona
ry

Di
cti
ona
ryo
per
ati
ons

Thedelst
atementr
emo
vesakey-v
aluepai
rf r
om adic
tion
a r
y.Fo
rex a
mple,t
hef o
llo
win
g
di
cti
ona
ryconta
inst
henameso
fvari
ousf
ruit
sa ndth
en umberofeac
hf ru
itinst
ock:

>>>i
nven
tor
y= {
app
les
:430,b
ana
nas
:31
2,o
ran
ges
:525,p
ear
s:21
7}

>>>p
rin
tin
ven
tor
y{o
ran
ges
:525,a
ppl
es:430,p
ear
s:21
7,b
ana
nas
:31
2}

I
fso
meo
neb
uysa
llo
fth
epea
rs,wec
anr
emo
vet
heen
tryf
romt
hedi
cti
ona
ry:

>>>deli
nven
tor
y[p
ear
s]

>>>p
rin
tin
ven
tor
y{o
ran
ges
:525,a
ppl
es:430,b
ana
nas
:31
2}

Ori
fwer
eex
pec
tin
gmo
rep
ear
sso
on,wemi
ghtj
ustc
han
get
hev
alu
eas
soc
iat
edwi
thp
ear
s:

>>>i
nven
tor
y[p
ear
s]= 0

>>>p
rin
tin
ven
tor
y{o
ran
ges
:525,a
ppl
es:430,p
ear
s:0,b
ana
nas
:31
2}

Th
elenf
unc
tio
nal
sowo
rkso
ndi
cti
ona
ries
;itr
etu
rnst
hen
umb
ero
fkey-v
alu
epa
irs
:
>>>l
en(
inv
ent
ory)4

7.Ex
pla
ini
ndet
aila
bou
tdi
cti
ona
rymet
hods
.

8.DI
CTI
ONARY METHODS

A met
hodi ssi
mil
artoaf u
nction
—ittakesarg
umentsandr et
urn
sav al
ue— butthesyn
taxi
s
di
ffer
ent.Forexamp
le,t
hek eysmetho
dt ak
esadi c
tio
n a
ryandr etu
rnsal i
stofthekeyst
hat
ap
pear,butins
tea
do fth
ef unct
ions
yntaxkeys(en
g2sp),weuset hemetho
ds ynt
ax
en
g2sp.
keys(
).

>>>en
g2s
p.k
eys
()[
one,t
hree,t
wo]

Thisfo
r mofdotnotati
onspecif
iesthenameo fthef u
nct
ion,k
eys,andt
henameoftheobject
toappl
yt hefun
ctionto,eng
2sp.Thep a
renthes
esi n
dic
atethatth
ismeth
odhasnopara
meters
.
A met
ho dcal
liscalleda ninv
ocat
ion
;int h
isc as
e,wewo u
ldsayt h
atwear
ei n
vok
ingkeyson
theobjecten
g2sp.

Th
eva
luesmet
hodi
ssi
mil
ar;i
tret
urn
sal
isto
fth
eva
luesi
nth
edi
cti
ona
ry:

>>>en
g2s
p.v
alu
es(
)[u
no,t
res
,do
s]

Th
eit
emsmet
hodr
etu
rnsb
oth
,int
hef
ormo
fal
isto
ftu
ples
—on
efo
rea
chk
ey-v
alu
epa
ir:
>>>en
g2s
p.i
tems
()[
(on
e,u
no)
,(t
hree,t
res
),(
two
,do
s)]

Thesynta
xp r
ovi
desu s
efu
ltypeinfo
r ma
t i
on.Thesquarebracket
sindic
atetha
tthisisalist
.
Theparenthes
esindic
atethattheelementso ft
hel is
ta r
et upl
es.Ifamethodtakesa
n
arg
umen
t,i tusesthesamesynt
axasaf uncti
oncall
.Fo rexampl
e,themeth
odh a
sk eytak
esa
keyandr etur
nstrue(1)ifthekeya ppearsinthedicti
onar
y:

>>>en
g2s
p.h
as_
key(
one)

Tr
ue

>>>en
g2s
p.h
as_
key(
deu
x)

Fa
lse

Ifyoutr
yt oc
allamet
hodwit
hou
tsp
eci
fyi
nga
nob
jec
t,yo
ugeta
ner
ror
.Int
hisc
ase,t
he
er
rormes
sag
eisnotv
eryhel
pfu
l:

>>>h
as_
key(
one)Na
meEr
ror
:ha
s_k
ey1
08

8.
Exp
lai
nindet
aila
bou
tli
stc
omp
reh
ens
ion.
Giv
eanex
amp
le.

Li
stc
omp
reh
ens
ion
s

Li
stc o
mpr
ehen
sio
nsp
rov
ideaco
n c
isewa
yt oc
rea
telis
ts.Itcon
sis
tso
fb racket
sc o
nta
inin
ga nexpr
ess
ion
fo
llo
wedb yaf o
rcl
aus
e,th
enzeroormor
eforori
fc lau
ses
.Theexpres
sio
nsc anbea n
ythi
ng,i
.e.
,al
l
k
indsofobject
scanbei
nli
sts
.Theres
ultwi
llbeanewl
istr
esul
tingfr
omeval
u a
tin
gt heex
pres
sio
nin
t
hec o
ntex
to fthefo
ran
difclau
seswh
ichfo
llo
wit
.Theli
stcompr
ehen
siona
lwaysretu
rnsaresu
ltlis
t.

Syn
tax

Th
eli
stc
omp
reh
ens
ions
tar
tswi
tha'
['a
nd'
]'
,toh
elpyo
urememb
ert
hatt
her
esu
lti
sgo
ingt
obeal
ist
.

Th
eba
sics
ynt
axi
s

[ex
pres
sio
nfo
rit
emi
nli
sti
fco
ndi
tio
nal]

Th
isi
seq
uiv
alen
tto
:

f
ori
temi
nli
st:

i
fco
ndi
tio
nal
:

ex
pres
sio
n

Lis
tcomp
rehen
sionisametho
dt odes
cri
bet h
ep r
oces
susi
ngwhichth
elists
hou
ldb ecrea
ted.To
dotha
t,theli
s tisbr
okeni
ntotwopi
eces.Thefi
rstisapic
tur
eo fwha
teachelemen
twilllook
li
ke,a
ndt h
es eco
ndiswhatisdon
et ogetit.

Fo
rin
sta
nce,l
et'
ssa
yweh
aveal
isto
fwo
rds
:
l
ist
OfWo
rds= [
"th
is"
,"
is"
,"
a",
"l
ist
",
"of
",
"wo
rds
"]

Tot
aket
hef
irs
tlet
tero
fea
chwo
rda
ndma
keal
isto
uto
fitu
sin
gli
stc
omp
reh
ens
ion
:

>>>l
ist
OfWo
rds= [
"th
is"
,"
is"
,"
a",
"l
ist
",
"of
",
"wo
rds
"]

>>>i
tems= [wo
rd[
0]f
orwo
rdi
nli
stOf
Wor
ds]

>>>p
rin
tit
ems

[
t'
,i'
,a'
,l'
,o'
,w'
]

Li
stcomp
rehen
sio
ns u
ppor
tsmor
et h
ano n
ef o
rs t
atemen
t.Itwil
leva
luat
etheit
emsi
na l
lofthe
ob
jec
tssequ
enti
allyandwil
lloopoverthesho
rterobjec
tsifoneob
jecti
slo
ngert
hanther
est
.

>>>i
tem = [
x+yf
orxi
nca
t'f
oryi
npo
t']

>>>p
rin
tit
em

[
cp'
,co
',c
t',a
p',a
o',a
t',t
p',t
o',t
t']

Lis
tcomp
rehens
ions
upp
ort
sani
fst
atemen
t,t
oon
lyi
ncl
udememb
ersi
ntot
hel
istt
hatf
ulf
illa
cer
tai
ncondi
tio
n:
>>>p
rin
t[x
+yf
orxi
nca
t'f
oryi
npo
t']

[
cp'
,co
',c
t',a
p',a
o',a
t',t
p',t
o',t
t']

>>>pri
nt[x+yforxi
nca
t'f
oryi
npo
t'i
fx!
=t'a
ndy!
=o']
[c
p',c
t',a
p',a
t']

>>>pri
nt[x+yf o
rxi ncat
'foryinp
ot'i
fx!
=t'o
ry!
=o']
[c
p',c
o',c
t',a
p',ao'
,at
',t
p',t
t']

9.
Wri
teaPyt
honp
rog
ramf
ora
)sel
ect
ions
ortb
)in
ser
tio
nso
rt.

SELECTI
ON SORT:

PROGRAM:

defs
elec
tio
nso
rt(a
Lis
t):

f
orii
n

r
ang
e(l
en(a
Lis

t))
:lea
st= i

f
orki
nra
nge(i+ 1,

l
en(a
Lis
t))
:if

a
Lis
t[k
]<a
Lis
t[l
eas
t]:
l
eas
t= k

s
wap
(aLi
st,l
eas
t,

i)defs
wap
(A,x
,y)
:

t
mp=

A[
x]A[
x]

= A[
y]

A[
y]= t
mp

a
Lis
t=

[
54,
26,
93,
1
7,77,
31,
44,
55,
20]

s
elec
tio
nso
rt(
aLi
st)

p
rin
t(a
Lis
t)

I
nser
tio
nso
rt:

defi
nser
tio
nSo
rt(
ali
st)
:

f
ori
ndexi
n

r
ang
e(1
,
len
(al
ist
)):

c
urr
ent
val
ue= a
lis
t[i
ndex
]

p
osi
tio
n= i
ndex
wh
ilep
osi
tio
n>0 a
nda
lis
t[p
osi
tio
n-

1
]>c
urr
ent
val
ue:a
lis
t[p
osi
tio
n]=a
lis
t[p
osi
tio
n-

1
]

p
osi
tio
n= p
osi
tio
n-1

a
lis
t[p
osi
tio
n]=c
urr
ent
val

u
e

a
lis
t=

[
54,
26,
93,
1
7,77,
31,
44,
55,
20]

i
nser
tio
nSo
rt(
ali
st)

p
rin
t(a
lis
t)

1
0.Wri
teaPyt
honp
rog
ramf
ora
)mer
ges
ortb
)qu
ick
s
ort
.

Mer
ges
ort
:

defmergeSort(
ali
st)
:
p
rint(
"Spli
tti
ng
"
,al
ist
)i f
l
en(ali
st)
>1:

mi
d= l
en(
ali
st)
//2
lefthalf=
ali
st[:mid]
rig
h t
h al
f=
ali
st[mid:]
mergeSo rt
(lefth
alf
)
mergeSo rt
(rig
hthal
f
)i =0

j
=0

k
=0

wh
ilei<l en(l
eft
hal
f)andj<
len(r
igh
th a
lf):i
fleft
hal
f[i
]<
rig
hthal
f[j]:

a
lis
t[k
]=l
eft
hal
f[i
]

i
=i+1

el
se:

a
lis
t[k
]=r
igh
tha
lf[
j]

j
=j+1

k
=k+1

wh
ilei<
len(
lefth
a l
f):
ali
st[
k]=lefth
alf
[i
]i=i+1

k
=k+1

wh
ilej<
len(
right
half)
:
ali
st[
k]=rig
hthal
f[j
]
j=j+1
k=k+1
p
rint(
"Mer
gin
g
"
,al
ist
)

ali
st=
[54,
26,93,
17,
77,
31,
44,
55,
20]
mergeSort
(al
ist
)

p
rin
t(a
lis
t)

Qu
ick
sor
t:

f
romr
ando
mimp
ortr
andr
ang
e

defp
art
iti
on(
lst
,st
art
,en
d,

p
ivo
t):

l
st[
piv
ot]
,ls
t[en
d]= l
st[
end]
,

l
st[
piv
ot]s
tor
e_i
ndex= s
tar
t

f
orii
nxr
ang
e(s
tar
t,

en
d):i
fls
t[i
]<

l
st[
end]
:

l
st[
i]
,ls
t[s
tor
e_i
ndex
]= l
st[
sto
re_
index
],

l
st[
i]s
tor
e_i
ndex+= 1

l
st[
sto
re_
index
],l
st[
end]= l
st[
end]
,

l
st[
sto
re_
index
]ret
urns
tor
e_i
ndex

defq
uic
k_s
ort
(ls
t,s
tar
t,

en
d):i
fst
art>= en
d:
r
etu
rnl
st

p
ivo
t= r
andr
ang
e(s
tar
t,en
d+ 1
)

n
ew_
piv
ot= p
art
iti
on(
lst
,st
art
,en
d,

p
ivo
t)q
uic
k_s
ort
(ls
t,s
tar
t,n
ew_
piv
ot

-1
)qu
ick
_so
rt(
lst
,new_
piv
ot+ 1
,

en
d)

defs
ort
(ls
t):

q
uic
k_s
ort
(ls
t,0,l
en(
lst
)

-1
)ret
urnl
st

p
rin
tso
rt(
[-5,3,-2,3,1
9,5]
)

p
rin
tso
rt(
[345,
45,
89,
569,
23,
67,
56,
90,
1
00]
)

1
1.Wr
iteaPyt
honp
rog
ramt
oimp
lemen
thi
sto
gra
m.

defhis
tog
ram(it
ems
)
:forni n
i
tems
:

o
utp
ut=
'
'ti
mes
=n
whi
le(t i
mes>
0) :outpu
t+=
'
*'times=
t
imes- 1

pr
int
(out
put
)
hi
sto
gram([
2,3,6,
5]
)

UNI
TV

FI
LES,MODULES AND PACKAGES

PART- A (
2 Ma
rks
)

1
.Wh
ati
sat
extf
ile?

Atextfi
leisafil
etha
tcont
ain
sp ri
ntabl
ech
ara
cter
san
dwh
ites
pac
e,
o
rga
niz
edi
nt oli
nessep
ara
tedbyn
ewli
nechara
cters
.

2.Wr
iteap yt
honprogr
amt h
atwr i
tes“
Hel
lowo
rld”i
ntoa
fi
le.f=open
("ex
88.t
xt",
'w'
)

f.
wri
te("
hello
wor
ld")f.c
lose(
)

3.Wr
iteap yt
honprog
ramt h
atco
unt
sth
enu
mbero
fwo
rdsi
na
fi
le.f
=open
("t
est.
txt
",
"r
")

co
ntent
=f.
readl
ine(20)
wor
ds
=cont
ent.
spl
it()
p
rin
t(wo
rds
)

4. Wh
ata
ret
het
woa
rgu
men
tst
akenbyt
heo
pen
()f
unc
tio
n?

Theopenfu
ncti
onta
kest
woa r
g u
ments:nameo
fth
efi
lea
ndt
hemo
deo
f
op
era
tion
.Exampl
e:f= o
pen
("test
.da
t",
"w"
)

5. Wh
ati
saf
ileo
bjec
t?

Afil
eo bjec
tall
owsustous
e,ac
cessan
dmanip
ulat
eal
lth
eus
era
cces
sib
le
f
iles
.Itmai
nta
insthesta
teab
outthefi
leithaso
pened.

6.Wh
atinfo
rma
tio
nisdisp
l a
yedi fwepr
intaf
ileo
bjec
tint
heg
iven
p
rog
ram?f=open
("test
.t
xt"
,"
w")

p
rin
tf

Th
ena
meo
fth
efi
le,mo
dea
ndt
hel
oca
tio
noft
heo
bjec
twi
llb
edi
spl
ayed.

7. Wh
ati
sanex
cep
tio
n?

When
everarun
timeerr
oro
ccu
rs,i
tc r
eat
esa
nex cep
tio
n.Thepr
ogr
amst
ops
ex
ecuti
onandpri
ntsa
nerr
ormess
age.Fo
rexamp
le,div
idi
ngbyzer
ocr
eatesa
n
ex
cepti
on:

p
rin
t55/
0

Zer
oDi
vis
ion
Err
or:i
nteg
erdi
vis
iono
rmo
dul
o

8.Wh
ata
ret
heer
rormes
sag
est
hata
redi
spl
ayedf
ort
hef
oll
owi
ngex
cep
tio
ns?

a
. Ac
ces
sin
gan
on-ex
ist
entl
isti
tem
b
. Ac
ces
sin
gak
eyt
hati
snti
nth
edi
cti
ona
ry

c
. Tr
yin
gtoo
penan
on-ex
ist
entf
ile

a
. I
ndex
Err
or:l
isti
ndexo
uto
fra
nge

b
. KeyEr
ror
:wh
at

c
. I
OEr
ror
:[Er
rno2]Nos
uchf
ileo
rdi
rec
tor
y:'
fil
ena
me'

9.Wh
ata
ret
het
wop
art
sina
ner
rormes
sag
e?

Theerr
ormess
ageha
st wopar
ts:th
et ypeo
fer
rorb
efo
ret
hec
olo
n,a
nd
sp
eci
_csab
outtheer
roraft
ert h
ec ol
on.

10.Howdoyouh
andl
eth
eex
cep
tio
nin
sideap
rog
ram wh
enyo
utr
ytoo
penan
on-
exis
ten
tfi
le?

f
ilen
ame= r
aw_
inp
ut(
'En
teraf
ile
n
ame:')t
ry:

f= open(fi
len
ame,
"
r")ex
c ep
tIOErro
r:

p
rin
t'Th
erei
snof
ilen
amed'
,fi
len
ame

1
1.Ho
wdo
est
rya
ndex
ecu
tewo
rk?

Thetrys
tatemen
tex ec
utest
hestat
ement
sinthefir
stblo c
k.I
fnoexcep
tion
oc
c u
rs,tenex
h ceptstat
ementisi
gnor
ed.Ifanexc
epti
onoft ypeIOEr
roro
ccurs
,it
execut
esthest
a t
ementsintheexc
eptbran
chandthencon
tin
u es
.

1
2.Wh
ati
sth
efu
nct
iono
fra
ises
tat
emen
t?Wh
ata
rei
tst
woa
rgu
men
ts?

Therai
sest
atementisus
edtorai
seanexcep
tio
nwh enth
ep ro
gramdetect
sa nerr
or.
Itta
kestwoargumen
ts:t
heexc
epti
ontyp
ea ndspec
ifi
cinfo
rmati
onabo
u ttheerr
or.

1
3.Wh
ati
sap
ickl
e?
Pick
lingsav
esanobj
ecttoafilefo
rl at
err et
rieval
.Thepi
ckl
emodul
ehelpsto
tr
ansla
tea l
mos
tanytypeofob
jecttoas tr
ingsu i
tabl
efors
tor
agei
nada t
abas
ea n
d
th
ent ran
sla
tethes
trin
gsba
ckintoo b
jects
.

1
4.Wh
ata
ret
het
womet
hodsu
sedi
npi
ckl
ing
?

Thet wometho
dsu
sedinp
ic k
lin
ga r
epick
le.
dump
()a n
dp ic
kl e.
loa
d()
.Tostor
eadata
st
ruct
u r
e,du
mpmetho
disuseda ndtol
oadtheda t
astru
cturest h
ataredu
mped,l
oad
meth
odi sus
ed.

1
5.Wh
ati
sth
eus
eoft
hef
orma
top
era
tor
?

Th
ef orma
to p
erator% t
akesaformatst
rin
ga ndatupl
eo fex
pres
sio
nsan
dyi el
ds
astr
ingthatinc
ludest
heex p
res
sio
ns,f
ormatt
edacc
ordin
gt ot
heformats
tri
ng.

1
6.Wh
ata
remo
dul
es?

A modu
lei
ss i
mplyafi
lethatdef
inesoneo
rmorerel
atedf
unct
ionsg
rou
ped
t
oget
her
.Toreus
et h
efun
cti
onsofag i
venmo
dul
e,weneedtoimpor
tthemodul
e.

Syn
tax
:imp
ort<mo
dul
ena
me>

1
7. Wh
ati
sap
acka
ge?

Pack
ag esar
en ames
pacest
hatc
ont
ainmu
lti
plep
ack
agesa
ndmo
dul
est
hems
elv
es.Th
ey
ar
es implydir
ector
ies
.

Syn
tax
:fr
om<myp
ack
age>i
mpo
rt<mo
dul
ena
me>

1
8.Wh
ati
sth
esp
eci
alf
ilet
hatea
chp
acka
gei
nPyt
honmu
stc
ont
ain
?

Ea
chp
ack
agei
nPyt
honmu
stc
ont
ainas
pec
ialf
ilec
all
ed_
_in
it_
_.p
y
1
9.Ho
wdoyo
udel
eteaf
ilei
nPyt
hon
?

Theremo
ve()meth
odi sus
edt
odel
etet
hef
ilesb
ysu
ppl
yin
gth
ena
meo
fth
efi
le
tobedelet
eda sarg
umen
t.

Syn
tax
:os
.r
emo
ve(
fil
ena
me)

20. Ho
wdoyo
uus
eco
mma
ndl
inea
rgu
men
tst
ogi
vei
npu
ttot
hep
rog
ram?

Pytho
nsysmodu
lep r
ovi
desa
ccesstoan
yc omman
d-l
inearg
umentsv
ias
ys.a
rgv.s
ys.
arg
v
istheli
stofcomma
nd-li
near
gumen
ts.l
en(
sys.
arg
v)isth
en umb
erofcommand-l
ine
arg
ument
s.

PART B (
16MARKS)

1
. Writ
eaf
unc
tio
nth
atc
opi
esaf
iler
eadi
nga
ndwr
iti
ngu
pto50 c
har
act
ersa
ta
ti
me.

defc
opyFi
le(
oldFi
le,n
ewFi
le)
:

f
1= o
pen
(ol
dFi
le,"
r")

f
2= open(
newFil
e,
"
w")wh
ileTrue:

t
ext=
f
1.
rea
d(50)if
t
ext== ""
:
b
reak

f
2.wr
ite(
tex
t)

f
1.
clo
se(
)

f
2.cl
ose(
)retu
rn
2. (
a)Wr
iteap
rog
ramt
oper
for
mex
cep
tio
nha
ndl
ing
.

defex
ist
s(fi
len
ame)
:
try:

f=
o
pen(fi
len
ame)
f
.cl
ose(
)

r
etu
rn
Trueexcep
t
IOErr
or:

r
etu
rnFa
lse

(
b)Wr
iteaPytho
np ro
gramtoh
andl
emu
lti
ple
exc
eptio
ns.tr
y:

x= f
lo a
t(ra
w_i
npu
t("
You
rnu
mber
:
")
)invers
e= 1.
0 /x

ex
cep
tVa
lueEr
ror
:

p
rin
t"Yous
hou
ldh av
eg i
venei
thera
nin
tor
af
loa
t"excep
tZer
oDi
vis
ion
Erro
r:

p
rin
t"I
nfi
nit
y"

3. Writ
eap yt
honp
rogr
amt ocou
ntn
umb
ero
fli
nes
,wo
rdsa
ndc
har
act
ersi
na
tex
tf i
le.defwor
dCoun
t():
c
l=0

c
w=0

c
c=0

f
=open
("ex
88.
txt
",
"r
"
)fo
rl i
neinf:

wo
rds
=li
ne.
spl
it(
)

c
l+=1

cw
+=len
(wo
rds)
cc+=len
(li
ne)

p
rin
t('
No.ofli
nes:'
,
cl)
p
rin
t('
No.ofwords:
',
cw)
p
rin
t('
No.of
c
harac
ter
s:'
,
cc)f.c
lose(
)

4. Wr
iteaPyt
honp
rog
ramt
oil
lus
tra
tet
heu
seo
fco
mma
nd-l
inea
rgu
men
ts.

i
mpo
rts
ys

defi
npu
tCmd(
):

p
rin
t( "
Nameo fthescri
pt:
",sys
.ar
gv[
0])
p
rin
t( "
Numb erofarg
u ment
s:"
,
l
en(s
ys.
argv)
)p ri
nt("Thea rg
ument
sa r
e:"
,
s
tr(
sys.
arg
v))
5.Mentio
nthec omma
ndsandtheirs
ynta
xf orth
ef o
llo
win
g:getcur
rentdi
rec
tory,
chan
gingdir
ect
ory,li
st,di
rec
tor
iesandfil
es,makeanewdir
ecto
ry,ren
ami
nga n
d
remov
ingdir
ect
ory.

(
a)Getcur
ren
tdir
ect
ory:
get
cwd(
)Synt
ax:i mp
ort
os

o
s.g
etc
wd(
)

(
a)Ch
ang
ingdi
rec
tor
y:c
hdi
r()

Syn
tax
:
o
s.c
hdir
(C:
\\User
s
)os.
get
cwd()

(
b)Lis
tdi r
ect
ori
esan
df iles
:
li
stdi
r()Synt
ax:o
s.l
ist
dir()

(
c)Ma
kin
gan
ewdi
rec
tor
y:mk
dir
()

Syn
tax
:os
.mk
dir
(Newdi
r)

(
d)Renamingadi recto
ry:
rename()
os.
rename(Newdir
,Newn
ame)
os.
lis
tdir(
)

(
e)Removi
ngadirec
t o
ry:
remo
ve()o
s.r
emove(NewNa
me)

6. Wr
iteaPyt
honp
rog
ramt
oimp
lemen
tst
acko
per
ati
onsu
sin
gmo
dul
es.
Mo
dul
edef
ini
tio
n:

def
g
etStac
k()
:
r
etur
n[]

def
i
sempty(
s):
i
fs ==[]
:

ret
urn
Tr
ueelse:

r
etur
n
Fals
edef
to
p(s):

i
f
isempty(
s):
return
No ne

el
se:

ret
urns[
len(
s)
-1
]defpush
(s,
it
em):

s
.ap
pend(
item
)defpop(
s):

i
f
isempty(
s):
return
No ne

el
se:
i
tem=s
[len
(s)
-
1
]
dels[
len
(s)
-1]r
etur
n
it
em

Pr
ogr
amt
oca
lls
tac
k:

i
mpo
rts
tac
k

deftoday()
:
myst
ack=st
ack.g
etSt
ack
(
)foritemi n
ra
nge(1
,7)
:

s
tack.
pus
h(myst
ack,
it
em)
p
rint
('Pu
shin
g',
it
em,
'to
s
tack'
)p r
int('
Stack
i
tems'
)

wh
ilen o
t
stack.
isemp
ty(myst
ack):
item=stack
.po
p(mysta
ck)
print
('Popi
ng'
,i
tem,
'fr
om
stack'
)

7. Wri
teap ro
gramt
oi l
lus
trat
emu lt
ipl
e
mo
dules
.impor
twor
dcoun
t,ex
12,
ex97
deftes
t():
wo
rdcou
nt.
wor
dCo
unt
()

deftes
t2()
:
ex
12.
in
put
Numb
er(
)

def
test
3():
ex97.f
un(
)

ex
97.
py:

def
f
un(
):
t
ry:

x= f
loat
(ra
w_i
npu
t("
You
rnu
mber
:
"
))inv
ers
e= 1.
0 /x

ex
cep
tVa
lueEr
ror
:

pr
int"Yous
hou
ldhav
eg iveneit
hera
nin
tor
af
loat"ex
cep
tZero
Divi
sio
nErro
r:

p
rin
t"I
nfi
nit
y"
ex
12.
py:

defi
npu
tNu
mber(
):

x= i
npu
t('Pi
cka
n
umb
er:')i
fx== 17:

r
ais
eVa l
ueEr
ror
,'1
7isab
ad
n
umber'r
eturnx

wor
dco
unt.
py:
def
wor
dCou
nt(
):

c
l=0

c
w=0

c
c=0

f
=open
("ex
88.
txt
",
"r
"
)fo
rl i
neinf:

wo
rds
=li
ne.
spl
it(
)cl+=1

cw
+=len
(wo
rds)
cc+=len
(li
ne)
p
rin
t('
No.ofli
nes:'
,
cl)
p
rin
t('
No.ofwords:
',
cw)
p
rin
t('
No.of
c
harac
ter
s:'
,
cc)f.c
lose(
)

8.Wr
iteaPyt
honprog
ramtodumpo
bjec
tst
oaf
ileu
sin
g
pi
ckl
e.imp
ortpic
kle

deff
unMa
p()
:

c
iti
es= ["
Chenna
i","del
hi"
,"
Mumb
ai"
,"
Kol
kat
a"]
f
h=open
("c
iti
es.
pck"
,"
w")

p
ick
le.
dump
(ci
ties
,fh
)

f
h.c
los
e()

f
=op
en(
"ci
ties
.pc
k",
"r
")

c
ts=p
ick
le.
loa
d(f
)

p
rin
t(c
ts)

You might also like