Python.use(better)

前の記事記事一覧次の記事
Python.use(better)


実録:はじめてのプログラミング《02》

本日のワンポイント

研修テキストでは、while/for が等価にならない事例として、break/continue について紹介しています。

def ex():
    for e in range(9):
        print(e,end=" ")
    print()

>>> ex()
0 1 2 3 4 5 6 7 8 

まず、比較したいもとの動作を確認しておきます。

def ex():
    for e in range(9):
         print(e,end=" ")
         if e>3: break
    print()

>>> ex()
0 1 2 3 4 
def ex():
    e = 0
    while e<9:
        print(e,end=" ")
        if e>3: break
        e += 1
    print()

>>> ex()
0 1 2 3 4 

次に、break の影響について考察します。

def ex():
    for e in range(9):
        print(e,end=" ")
        if e>3: continue
    print()

>>> ex()
0 1 2 3 4 5 6 7 8
def ex():
    e = 0
    while e<9:
        print(e,end=" ")
        if e>3: continue
        e += 1
    print()

>>> ex()
0 1 2 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
Traceback (most recent call last):
  ...
KeyboardInterrupt
    
そして、continue の影響について考察します。

Tips

この課題は、プログラムが暴走(無限ループなど)したときの対処法を伝授する好機にもなります。《ひよ子》
Last updated♪09/03/01