
Yamu
今回は繰り返し
処理の基本(for文)
を学びます
合わせて読みたい |
【アルゴリズム】pythonで繰り返し(while)処理を学ぶ |
繰り返し処理とは?
特定の操作や処理を何度も実行するための仕組み
forループは、指定された回数だけ処理を繰り返す場合に使用されます


Yamu
カウンタを作って
決まった回数
処理を行い
終わったら抜ける
アルゴリズムなんですね
for文
forループは、指定された回数だけ処理を繰り返す
for i in range(0, 3):
print(f" i = {i}")
実行結果

表を使って処理を確認します
ループ | i |
初期値0をfor変数に格納する | 0 |
処理 | |
for(iを0から2まで1ずつ増やす) | 1 |
処理 | |
for(iを0から2まで1ずつ増やす) | 2 |
処理 | |
ループから抜ける |

Yamu
処理は
3回繰り返されて
いますね!
初期値、終値の後に増減を
加えることで繰り返しの回数を
調整することが出来ます
for i in range(0, 5, 2):
print(f" i = {i}")


Yamu
2ずつ増えてる!
for文はリスト、タプル、セットなどのオブジェクトでも有効
for文はリスト、タプル、セット、
文字列などの反復可能なオブジェクト
に対しても使用できます
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)

emumerate関数を使うと
インデックスと要素を同時に取得できます
animals = ['cat', 'dog', 'rabbit']
for index, animal in enumerate(animals):
print(f"Animal at index {index} is {animal}")

breakとcontinue
breakは繰り返しを中断する
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
if fruit =="banana":
break
print(fruit)
実行結果


Yamu
cherryループに入らず
bananaループで
ループ処理を
抜けていますね !
continueは繰り返しの先頭に戻る
for i in range(0, 10):
if i < 5:
continue
print(f"i = {i}")
