008:繰り返し
繰り返しには、while文とfor文があります。
while文は他の言語と同じように、条件が真の間だけ繰り返されます。
>>> x=100
>>> count=0
>>> while x>10:
x=x/2
count=count+1
print count,x
1 50
2 25
3 12
4 6
Python の for 文は、任意の配列型 (リストまたは文字列) にわたって反復を行います。反復の順番は配列中に要素が現れる順番です。 例えば 、
>>> # いくつかの文字列の長さを測る: ... a = ['cat', 'window', 'defenestrate'] >>> for x in a: ... print x, len(x) ... cat 3 window 6 defenestrate 12
複数の配列型をまとめて反復するには、zip関数を使います。
>>> a=['apple','orange','lemon'] >>> b=[10,20,30] >>> for fruit,qty in zip(a,b): ... print "There are",qty," ",fruit ... There are 10 apple There are 20 orange There are 30 lemon
ループの制御にはbreakやcontinueが使えます。
>>> for i in range(0,10): ... if i < 5: ... continue ... print i ... 5 6 7 8 9
176:回数を指定して処理を繰り返すも参照のこと。