1. ホーム 
  2. 備忘録 
  3. Python

反復処理

while文

反復処理を実現する while文 の例を以下に記載する


# while 条件式パターン
count = 0
while count < 5:
    print(count)
    count += 1
"""
結果
0
1
2
3
4
"""

# while Trueパターン
count = 0
while True:
    if count >= 5:
        break
    print(count)
    count += 1
"""
結果
0
1
2
3
4
"""

# continue の使い方
count = 0
while count < 5:
    if count < 3:
        count += 1
        continue
    print(count)
    count += 1
"""
結果
3
4
"""

# while~else のパターン
#   else の処理は break されたときは行わない点に注意する
count = 0
while count < 5:
    print(count)
    count += 1
else:
    print('count が5以上になったので while ループを抜けました')
"""
結果
0
1
2
3
4
count が5以上になったので while ループを抜けました
"""

# break で抜けるパターン
count = 0
while count < 5:
    if count == 3:
        break
    print(count)
    count += 1
else:
    print('count が5以上になったので while ループを抜けました')
"""
結果
0
1
2
"""

for文

反復処理には while文 のほかに for文 も使用できる

for文 の例を以下に記載する


some_list = [1, 2, 3, 4, 5]

# for文ならイテレータ―で回せる
for i in some_list:
    print(i)
"""
結果
1
2
3
4
5
"""


# for文でも break や continue が使える
for word in ['My', 'name', 'is', 'Mike']:
    if word == 'name':
        continue
    if word == 'Mike':
        break
    print(word)
"""
結果
My
is
"""


# for~else のパターン
#   else の処理は break されたときは行われない点に注意する
for fruit in ['apple', 'banana', 'orange']:
    print(fruit)
else:
    print('I ate all!')
"""
結果
apple
banana
orange
I ate all!
"""

# break で抜けるパターン
for fruit in ['apple', 'banana', 'orange']:
    if fruit == 'banana':
        print('stop eating')
        break
    print(fruit)
else:
    print('I ate all!')
"""
結果
apple
stop eating
"""

range関数

for文とともにrange関数を使うと『同じ処理をn回行いたい』といった仕組みを簡単に実現できる

range関数の使い方は以下の通りである


# 0 <= i < 10 までループ
for i in range(10):
    print(i, end=',')  # 0,1,2,3,4,5,6,7,8,9,

# 2 <= i < 10 までループ
for i in range(2, 10):
    print(i, end=',')  # 2,3,4,5,6,7,8,9,

# 2 <= i < 10 まで 3個飛ばしでループ
for i in range(2, 10, 3):
    print(i, end=',')  # 2,5,8,


"""
' _ (アンダーバー)'を使うと i の部分が不要であることが明示的にできるので、
コードを見る側がわかりやすいメリットがある
"""
# _ を使ったfor文
for _ in range(10):
    print('Ya', end='-')  # Ya-Ya-Ya-Ya-Ya-Ya-Ya-Ya-Ya-Ya-