こんにちは。
本日は、Pythonメモです。
概要
反復処理はコードを書く上で絶対使いますよね。
ただ、反復処理をするだけではなく、
whileにもforにも、break、continue、elseといった
処理を制御するためのものがあるので
本記事では、上記を使ってみようと思います。
whileを使った反復処理
breakを使用した処理の中断
break
を使用すると反復処理を中断することができます。
無限ループの場合でも、終了することができます。
colors = ['red', 'blue', 'yellow', 'green'] index = 0 while True: color = colors[index] print(color) if color == 'yellow': print('color is yellow!!') break index += 1
実行結果は以下です。
red blue yellow color is yellow!!
continueを使った次のイテレーションの開始
continue
は、処理を中断するのではなく
その時点で次のイテレーションを開始することができます。
colors = ['red', 'blue', 'yellow', 'green'] index = 0 while index < len(colors): color = colors[index] index += 1 if color == 'yellow': print('color is yellow!!') continue print(color)
実行結果は以下です。
red blue color is yellow!! green
elseを使ってbreakしたか判定
breakせずに、ループが終了すると
else
が設定されている場合は、else節の処理が実行されます。
colors = ['red', 'blue', 'yellow', 'green'] index = 0 while index < len(colors): color = colors[index] print(color) if color == 'black': break index += 1 else: print('black does not exist')
実行結果は以下です。
red blue yellow green black does not exist
forを使った反復処理
breakを使用した処理の中断
break
を使用するとwhileと同様に反復処理を中断することができます。
colors = ['red', 'blue', 'yellow', 'green'] for color in colors: print(color) if color == 'yellow': print('color is yellow!!') break
実行結果は以下です。
red blue yellow color is yellow!!
continueを使った次のイテレーションの開始
continue
もwhileと同様に、処理を中断するのではなく
その時点で次のイテレーションを開始することができます。
colors = ['red', 'blue', 'yellow', 'green'] for color in colors: print(color) if color == 'yellow': print('color is yellow!!') continue
elseを使ってbreakしたか判定
else
もwhileと同様です。
breakせずに、ループが終了すると
else
が設定されている場合は、else節の処理が実行されます。
colors = ['red', 'blue', 'yellow', 'green'] for color in colors: print(color) if color == 'black': break else: print('black does not exist')
以上です。