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

More than 3 years have passed since last update.

【Python】for文がbreakされず要素すべて実行されたのかをfor-elseで判定する方法(備忘録)

Last updated at Posted at 2021-03-30

自分用メモ

for文がbreakで途中で抜けたのか、breakされず要素すべて実行されたのか判定する方法。
他の言語のクセでbool型で途中で抜けたのかを判定しがちだったけどこれは便利。

for-else

weeklist =  ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
for day in weeklist:
    print('day:' + day)
    if day == 'April':
        break
else:
    print('最後までループしたよ')

print('for文が終了したよ')
day:Sunday
day:Monday
day:Tuesday
day:Wednesday
day:Thursday
day:Friday
最後までループしたよ
for文が終了したよ

bool型での判定

よく書きがちだった方法

weeklist =  ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
isBreak = False
for day in weeklist:
    print('day:' + day)
    if day == 'April':
        isBreak = True
        break
if not isBreak:
    print('最後までループしたよ')

print('for文が終了したよ')

以上

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