1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

break / continue の動きを理解する【Day 12】

1
Last updated at Posted at 2025-12-11

Qiita Advent Calendar 2025 のパイソニスタの一人アドカレ Day12 の記事です。

break / continue の動きを理解する

ループ処理(for / while)では、途中でループを抜けたり、1回分の処理をスキップしたくなることがあります。
そんなときに使うのが break と continue です。

break:ループを途中で抜ける

「もうループを続けなくていい」と判断したら使います。

for n in [1, 2, 3, 4, 5]:
    if n == 3:
        break
    print(n)

実行結果:

1
2

n == 3 の時点でループそのものが終了します。

continue:その回だけスキップ

「この条件のときは処理したくない」場合に便利です。

for n in [1, 2, 3, 4, 5]:
    if n == 3:
        continue
    print(n)

実行結果:

1
2
4
5

3 のときだけ表示がスキップされます。

while 文でも同じ

count = 0

while count < 5:
    count += 1
    if count == 2:
        continue
    if count == 4:
        break
    print(count)

break / continue の使い分け

やりたいこと 使うもの
ループ自体を終わらせたい break
その1回だけ飛ばしたい continue

よくあるミス

continue の後に処理を期待してしまう

for n in [1, 2, 3, 4, 5]:
    if n == 3:
        continue
    print("これは実行されません")

continue の行が実行されたら同じループの中の残りの処理はすべてスキップされます。

まとめ

  • break → ループを途中で終了
  • continue → その回だけスキップ
  • for / while のどちらでも利用可能
  • ループの流れを制御する重要なテクニック
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?