Python while文のelse句 質問する

Python while文のelse句 質問する

次のコードは Python では合法であることに気付きました。質問はなぜでしょうか? 特別な理由があるのでしょうか?

n = 5
while n != 0:
    print n
    n -= 1
else:
    print "what the..."

if多くの初心者は、 /ブロックをまたはループelse内に配置しようとしてを適切にインデントしないときに、この構文に誤って遭遇します。解決策は、ブロックを と揃えることです。これは、ブロックと をペアにすることが意図されていたと仮定した場合です。この質問では、構文エラーが発生しなかった理由と、結果のコードが何を意味するかを説明します。whileforelseelseifIndentationError が発生しています。どうすれば修正できますか?構文エラー報告された場合。

参照Python はなぜ for ループと while ループの後に 'else' を使用するのでしょうか?機能の有効活用方法に関する質問については、

ベストアンサー1

この句は、条件が偽になったelse場合にのみ実行されます。ループから外れた場合、または例外が発生した場合は、実行されません。whilebreak

これについて考える方法の 1 つは、条件に関する if/else 構造として考えることです。

if condition:
    handle_true()
else:
    handle_false()

ループ構造に類似しています:

while condition:
    handle_true()
else:
    # condition is false now, handle and go on with the rest of the program
    handle_false()

たとえば次のようなものが考えられます。

while value < threshold:
    if not process_acceptable_value(value):
        # something went wrong, exit the loop; don't pass go, don't collect 200
        break
    value = update(value)
else:
    # value >= threshold; pass go, collect 200
    handle_threshold_reached()

おすすめ記事