Pythonでforループする方法

投稿者: | 2020年10月12日

Pythonでforループする方法です

rangeを使った場合  range(start, stop, step)

breakは処理中断

for i in range(1, 6):
    if i == 3:
        break
    print(i)

実行結果

1
2

continueは処理スキップ

for i in range(1, 6):
    if i == 3:
        continue
    print(i)

実行結果

1
2
4
5

配列を使った場合

test = ['1', '2', '3', '4', '5']

for no in test:
    print(no)

実行結果

1
2
3
4
5

一部の要素のみ取り出す場合 スライス [start:stop:step]

for no in test[1::2]:
    print(no)

実行結果

2
4