Python continue 文
continuePythonで今回のループをスキップして次の反復に入るために使用されるキーワードです。
とbreak異なり、continueループ全体を終了させるのではなく、現在のループの残りのコードをスキップするだけです。
単語の意味: continue「続ける」という意味で、現在の反復をスキップして次の反復に進みます。
基本構文とパラメータ
continue独立した文であり、パラメータは一切必要ありません。
構文形式
for item in iterable:
if 跳过条件:
continue
# 处理代码
使用シーン
- 特定の要素をスキップ: 条件を満たす場合に処理をスキップします。
- データのフィルタリング: 条件に合わないデータを除外します。
- ロジックの簡略化: 「処理しない」条件を先に置き、ネストを減らします。
例
例1:偶数をスキップ
例
# 1から10までの奇数を出力
for i in range(1, 11):
if i % 2 == 0:
continue # 偶数をスキップ
print(i, end=" ")
print()
# 出力: 1 3 5 7 9
for i in range(1, 11):
if i % 2 == 0:
continue # 偶数をスキップ
print(i, end=" ")
print()
# 出力: 1 3 5 7 9
実行結果の予想:
1 3 5 7 9
コード解説:
- iが偶数の場合は、continueを実行して後続のprintをスキップします。
- iが奇数の場合は、通常通りprintを実行します。
例2:リスト要素をフィルタリング
例
# 空の値とNoneを除外
data = ["apple", None, "", "banana", " ", "cherry"]
# 方法1:continueを使用
result = []
for item in data:
if not item: # 空文字列またはNoneはFalse
continue
result.append(item)
print(result) # 出力: ['apple', 'banana', ' ', 'cherry']
# 方法2:有効なものだけを処理
print("有効なデータ:")
for item in data:
if item: # 空でなく、Noneでもない
print(f"- {item}")
data = ["apple", None, "", "banana", " ", "cherry"]
# 方法1:continueを使用
result = []
for item in data:
if not item: # 空文字列またはNoneはFalse
continue
result.append(item)
print(result) # 出力: ['apple', 'banana', ' ', 'cherry']
# 方法2:有効なものだけを処理
print("有効なデータ:")
for item in data:
if item: # 空でなく、Noneでもない
print(f"- {item}")
実行結果の予想:
['apple', 'banana', ' ', 'cherry'] 有效数据: - apple - banana - - cherry
continueはデータのフィルタリングに使用でき、不要な要素を除外できます。
例3:whileループでの使用
例
# 特定の数字をスキップするシミュレーション
n = 0
while n < 10:
n += 1
if n == 5 or n == 7:
continue # 5と7をスキップ
print(n, end=" ")
print()
# 出力: 1 2 3 4 6 8 9 10
n = 0
while n < 10:
n += 1
if n == 5 or n == 7:
continue # 5と7をスキップ
print(n, end=" ")
print()
# 出力: 1 2 3 4 6 8 9 10
実行結果の予想:
1 2 3 4 6 8 9 10
whileループ内でのcontinueの役割も同じです。
例4:コードロジックの簡略化
例
# continueを使用してロジックを簡略化
numbers = [1, 2, -3, 4, -5, 6, -7]
# continueを使用しない場合(ネストが深い)
print("正の数(方法1):")
for n in numbers:
if n > 0:
print(n)
print("\n正の数(方法2)- continueを使用):")
for n in numbers:
if n <= 0:
continue
print(n)
print("\n負の数:")
for n in numbers:
if n >= 0:
continue
print(n)
numbers = [1, 2, -3, 4, -5, 6, -7]
# continueを使用しない場合(ネストが深い)
print("正の数(方法1):")
for n in numbers:
if n > 0:
print(n)
print("\n正の数(方法2)- continueを使用):")
for n in numbers:
if n <= 0:
continue
print(n)
print("\n負の数:")
for n in numbers:
if n >= 0:
continue
print(n)
実行結果の予想:
continueを使用すると、コードをよりフラットにし、ネストを減らすことができます。
例5:ネストされたループ内のcontinue
例
# continueは現在のループにのみ影響します
for i in range(1, 4):
for j in range(1, 4):
if j == 2:
continue # 内側のループの今回の反復をスキップ
print(f"({i},{j})", end=" ")
print()
for i in range(1, 4):
for j in range(1, 4):
if j == 2:
continue # 内側のループの今回の反復をスキップ
print(f"({i},{j})", end=" ")
print()
実行結果の予想:
(1,1) (1,3) (2,1) (2,3) (3,1) (3,3)
continueは、それを含む最内側のループの現在の反復のみをスキップします。
その他の拡張
Python3 ループ文