01-1.py
01-1.py
''
Pythonprovi
dest
hef
oll
owi
ngl
oops
1)whil
eloop
2)forl
oop
whil
el oop
==========
Awhi l
el oopr
epeti
ti
vlyexecutesatargets
tat
ementorbl
ockofs
tat
ement
sasl
ongas
thegiven
condi
dt i
onintheexpres
sionistrue.
syntax
-
----
-
whileexpres
sion:
st
atementblock
'
'
'
#Pr
ogr am t
opr i
ntal
lnat
uralnumberupt
o100
#n=1
#whil
en<=1 00:
# pri
nt(
n)
# n+=1
'
''
i
nOper ator
============
Thei n oper at
or ( als
o known asmember shi
p oper
at or
)isused f
orcont
ainment
checkinginacont ainer.
Theoper atorret
urnsTrueorFalsedependi
ngonwhet hertheel
ementispr
esentin
thecont ainerornot.
'
'
'
#pr
int
('
s'in'
Comput er
')
#pr
int
('
e'in'
Hello')
#pr
int
(10in[20,
1 0,
60])
#pr
int
(1in(1
,2,3) )
#pr
int
(8in{8,50,60,1 0}
)
'
''
forLoop
=========
I
Ti ss ui
tedfortheprobl
em wher
ewehavepr
iorknowl
edgeoft
henumberoft
imes
thes t
atementorblock
willbeexecuted.
Syntax
--
---
-
f
orvari
nsequence:
s
tat
ementblock
'
'
'
#Program toprintel
ement
sofal
ist
#li
st1=[1
5,1 6,1
0,8]
#forii
nlist
1:
# pri
nt(i
)
#Program topri
ntel
ement
sofat
upl
e
#t=(15,16,10,8)
#forii
nt:
# pri
nt(i
)
#Program topri
ntel
ement
sofas
et
#s={ 1
5,16,10,8}
#forii
ns:
# pri
nt(i
)
#Program t
oprintDictionary
#1.I
terat
eoverkeys
#d={ '
C':
68,'
DS':
55,'Python':87,'
Algo':
74,'
CO':68}
#forii
nd.keys(
): #keys (
)met hodreturnsli
stofallkeys
# pri
nt(
"Subject
:{},Mar ks:{}
".
format(i
,d[
i]
))
#2.It
erateoverKey- Valuepair
#d={ '
C':68,'
DS':
55,'
Python':87,'
Algo':
74,'CO':
68}
#fori,
jind.it
ems(): #items()met hodreturnsali
stofel
ement
s(key,val
ue)ast
upl
es
# print(
"Subj
ect:{}
,Mar ks:{}
".
format(i
,j)
)
'
''
range()Funct
on
===============
i
sus edtogenerat
eani
mmut
abl
esequenceofnumber
s.
r
ange(
star
t,s
top,s
tep)
st
art:anintegervalueatwhi cht hesequencebegi ns
;ifnotspeci
fi
edthenitbeginsa
0.
st
op:i salwaysr equi
red and s peci
fi
est he i
ntegert hati
scount ed up t
o butnot
i
ncluded.
st
ep:specif
ieshow mucht oincreaseordecreas ethenextit
erati
on
syntax
-
----
-
f
orvari nrange(
start
,st
op,s
tep)
:
st
atementblock
'
'
'
#print1to10
#foriinrange(1
,11
,1)
:
# pr
int(
i)
#pri
ntli
stit
emsus i
ngindex
#l
ist
1=[ 1
0,20,30,40,50,60,70]
#n=l
en(li
st1
)
#pri
nt(
"Elementsi
nt hel
istatoddpos
iti
ti
onar
e:"
)
#forii
nrange(0,n,2)
:
# pri
nt(
li
st1
[i])
'
''
NestedLoop
===========
Theloop i ns
ideanot herloop.
'
''
#foriinrange(6):
# forjinrange(1,
3,1)
:
# pri
nt(i
,""
,j
)
#Program tofi
ndcommonel ement soft
wol
ist
sus
ingnes
tedl
oop
#li
st1=[1
0,12,58,33,22,50,49,25]
#li
st2=[5,12,2,22,49,1
3,99,78,10]
#foriinl
ist
1:
# forji
nlist2:
# i
fi==j :
# pr i
nt(
i)
'
''
elseClauseinloop
===================
i
sexecut edonl yifthel
oopter
minat
esnor
mal
ly,i
.e.
,ter
minat
est
hroughexhaus
tion
oftheiterable.
'
''
foriinrange(10):
pri
nt(i
)
#ifi==6:
# br
eak
else:
pri
nt('
els
ecl aus
eexecut
ed'
)