の続き。よくよく考えたら前回「なんでだろう」といっていたコードは x == 5 のときの動作が break 文だけであった。だから理解するのに時間がかかったのだ(たぶん)。なので x == 5 のときに print 文を実行するようにしたのが下記。(ちなみに executed の和訳は実行されるという意味)
>>> for x in range(0,10): ... if x == 5: ... print 'break is executed.' ... break ... else: ... print 'break is NOT executed.' ... break is executed.
実行結果が x == 5 のときの 1 回だけというのはなぜか。
0 から 4 までの 5 回分 print 文が実行されて
http://d.hatena.ne.jp/ryskosn/20100925/1285381124
break is not executed.
break is not executed.
break is not executed.
break is not executed.
break is not executed.
こういうふうになると思ったのだけれども。なんでだろう。
前回もこう書いたように、0 から 4 までの 5 回分はどうなるのか、と考えていたら気づいた。インデントだ。上記↑のコードだと else 節が実行されるのは「for 文がリストを使い果たしたりしてループが終了したとき」と「Python チュートリアル」に書いてあった。
そこで else 節のインデントを一段、内側に変更してみる。
>>> for x in range(0,10): ... if x == 5: ... print 'break is executed.' ... break ... else: ... print 'break is NOT executed.' ... break is NOT executed. break is NOT executed. break is NOT executed. break is NOT executed. break is NOT executed. break is executed.
↑これだと if 節「x == 5 のとき」、else 節「x が 5 じゃないとき」という処理になるので 0 から 4 までの 5 回分は else 節のほうが実行されるようになる。
for がリストを使い果たしたとき、つまり 0 から 9 までの値を入れていっても if 文の条件に合致するものがないとき、も試してみた。
>>> for x in range(0,10): ... if x == 13: ... print 'break is executed.' ... break ... else: ... print 'break is NOT executed.' ... break is NOT executed.
x == 13 を条件にしたところ、あてはまるものはないので else 節が実行される。
すこしわかった気がする。