LoginSignup
0
0

More than 3 years have passed since last update.

【Python】while文がbreakされず条件を満たすまで実行されたのかをwhile-elseで判定する方法(備忘録)

Last updated at Posted at 2021-03-31

自分用メモ

while文がbreakで途中で抜けたのか、breakされず条件を満たす間すべて実行されたのか判定する方法。
他の言語のクセでbool型で途中で抜けたのかを判定しがちだったけどこれは便利。
for文で出来たのでwhile文で試してみたら出来た。

for-else

while-else

counter = 0
while(counter < 5):
    print("while中だよ")    
    counter += 1
    if counter == 10:
        break
else:
    print('最後までループしたよ')
print('while文が終了したよ')
while中だよ
while中だよ
while中だよ
while中だよ
while中だよ
最後までループしたよ
while文が終了したよ

bool型での判定

よく書きがちだった方法

counter = 0
isBreak = False
while(counter < 5):
    print("while中だよ")    
    counter += 1
    if counter == 10:
        isBreak = True
        break
if not isBreak:
    print('最後までループしたよ')
print('while文が終了したよ')

以上

0
0
1

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
0
0