0
0

python for文のelse

Posted at

for文内のelse:の後に、for文内のbreakが実行されなかった場合に実行する処理を記述できる。
つまり、ループが最後まで実行された後にのみ実行される処理を記述できる。

Example

arr_ = [1,2,3,4,5]

for ar in arr_:
    if ar % 2 == 0:
        print(ar)
        break
else:
    print("even number is nothing")

リストarr_の中に偶数が含まれる場合、ifブロックの処理が実行されbreakによりforループの処理が中断される。この場合、else:以降のコードは実行されない。

一方、リストarr_の中に偶数が含まれない場合、breakは実行されずにforループは最後まで(arr_の最後の要素まで)実行される。この場合、else:以降のコードが実行される。

reference - Excel VBAなら

Dim arr_() As Variant
arr_ = Array(1, 2, 3, 4, 5)
Dim i As Long
For i = LBound(arr_) To UBound(arr_)
    If arr_(i) Mod 2 = 0 Then
        Debug.Print arr_(i)
        Exit For
    End If
Next i
    
If i = UBound(arr_) + 1 Then Debug.Print "even number is nothing"

python のfor…else:…と同様の処理をするには、上記のような感じでしょうか。。

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