while の基本的な使い方
条件 が真の間、コロン(:)に続く、インデントされたブロックを繰り返し実行します。while <条件>:
<条件が真の時に繰り返す処理>
次のサンプルコードは 'Hello, while!' を 10回 表示します。
index = 0
while index < 10:
index = index + 1
print(f'{index} Hello, while!')
while 到達時に 条件が 偽 の場合
while 内の処理は実行されません。次のサンプルコードは whileの直前に条件を満たさなくなっているので、何も表示されません。index = 100
while index < 10:
index = index + 1
print(f'{index} Hello, while!')
break - ループを抜ける
break を使用すると、while の条件が 真 でもループを抜けます。次のサンプルコードは break を使用し、'Hello, while!' を 10回 表示します。
index = 0
while True: # 無限ループ
index = index + 1
if index > 10:
# ループを抜ける
break
print(f'{index} Hello, while!')
continue - ループの先頭に戻る
continue を使用するとループの先頭に戻り、while の条件判定が行われます。次のサンプルコードは continue を使用し、'Hello, while!' を 5回 表示します。
index = 0
while index < 10:
index = index + 1
if index > 5:
# ループの先頭に戻る
continue
print(f'{index} Hello, while!')
else - ループ終了時に処理を実施
while の条件が 偽 になると elseブロックが実行されます。break や return でループを抜けたときは実行されません。while <条件>:
<条件が真の時に繰り返す処理>
else:
<条件が偽になったときに実行する処理>
次のサンプルコードは 'Hello, while!' を 10回 表示したあと、'end, while!' を表示します。
index = 0
while index < 10:
index = index + 1
print(f'{index} Hello, while!')
else:
print('end, while!')
次のサンプルコードは 'end, while!' のみ表示されます。
while False:
print('Hello, while!')
else:
print('end, while!')
次のサンプルコードは何も表示されません。
while True: # 無限ループ
# ループを抜ける
break
else:
print('end, while!')
while True: # 無限ループ
# 呼び元に戻る
return
else:
print('end, while!')
参考資料
検証環境
- Python 3.11.3 (tags/v3.11.3:f3909b8, Apr 4 2023, 23:49:59) [MSC v.1934 64 bit (AMD64)] on win32
- Microsoft Windows 10 Enterprise Version 22H2 OS Build 19045.3693 Experience: Windows Feature Experience Pack 1000.19053.1000.0