if句を途中で終了するためにどのような方法が存在しますか?
コードを書いていて、break文をif句の中に入れたい場合があります。それらはループにしか使用できないことを覚えておいてください。
例として次のコードを見てみましょう:
if some_condition:
...
if condition_a:
# do something
# and then exit the outer if block
...
if condition_b:
# do something
# and then exit the outer if block
# more code here
これを行う1つの方法を考えることができます。ネストされたifステートメント内で終了ケースが発生すると想定して、残りのコードを大きなelseブロックでラップします。例:
if some_condition:
...
if condition_a:
# do something
# and then exit the outer if block
else:
...
if condition_b:
# do something
# and then exit the outer if block
else:
# more code here
これの問題は、より多くの出口位置がより多くのネスト/インデントされたコードを意味することです。
あるいは、if節をできるだけ小さくして出口を必要としないようにコードを書くこともできます。
誰かがif句を終了するための良い/より良い方法を知っていますか?
関連するelse-ifおよびelse句がある場合、終了するとそれらがスキップされると思います。
if a: #stuff; #stuff_inbetween; if b: #stuff;、中間コードはにnot a依存しbますが、依存しません。
elif stackoverflow.com/a/2069680/7045119
elif?