130

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句がある場合、終了するとそれらがスキップされると思います。

4

13 に答える 13

128

(このメソッドは、ifs、複数のネストされたループ、および簡単に実行できないその他の構造に対して機能しますbreak。)

コードを独自の関数でラップします。の代わりにbreak、を使用しますreturn

例:

def some_function():
    if condition_a:
        # do something and return early
        ...
        return
    ...
    if condition_b:
        # do something else and return early
        ...
        return
    ...
    return

if outer_condition:
    ...
    some_function()
    ...
于 2010-01-15T05:24:07.360 に答える
73
gotoからインポートgoto、ラベル

some_conditionの場合:
   ..。
   condition_aの場合:
       #何かをする
       #次に、外側のifブロックを終了します
       goto .end
   ..。
   condition_bの場合:
       #何かをする
       #次に、外側のifブロックを終了します
       goto .end
   #ここにもっとコード

label .end

(実際には使用しないでください。)

于 2010-01-15T05:29:47.377 に答える
31
while some_condition:
   ...
   if condition_a:
       # do something
       break
   ...
   if condition_b:
       # do something
       break
   # more code here
   break
于 2010-01-19T02:05:03.893 に答える
12

例外を除いて、gotoの機能をエミュレートできます。

try:
    # blah, blah ...
    # raise MyFunkyException as soon as you want out
except MyFunkyException:
    pass

免責事項:私はあなたの注意をこのように行う可能性をもたらすことを意味するだけですが、通常の状況下でそれを合理的であると保証することは決してありません。質問へのコメントで述べたように、そもそもビザンチンの条件を回避するようにコードを構造化することがはるかに望ましいです。:-)

于 2010-01-15T05:35:05.340 に答える
9

これかも?

if some_condition and condition_a:
       # do something
elif some_condition and condition_b:
           # do something
           # and then exit the outer if block
elif some_condition and not condition_b:
           # more code here
else:
     #blah
if
于 2010-01-15T05:28:19.403 に答える
7

実際に尋ねられたのは、私のアプローチはそれらifを1ループのループ内に置くことです

while (True):
    if (some_condition):
        ...
        if (condition_a):
            # do something
            # and then exit the outer if block
            break
        ...
        if (condition_b):
            # do something
            # and then exit the outer if block
            break
        # more code here
    # make sure it is looped once
    break

試して:

conditions = [True,False]
some_condition = True

for condition_a in conditions:
    for condition_b in conditions:
        print("\n")
        print("with condition_a", condition_a)
        print("with condition_b", condition_b)
        while (True):
            if (some_condition):
                print("checkpoint 1")
                if (condition_a):
                    # do something
                    # and then exit the outer if block
                    print("checkpoint 2")
                    break
                print ("checkpoint 3")
                if (condition_b):
                    # do something
                    # and then exit the outer if block
                    print("checkpoint 4")
                    break
                print ("checkpoint 5")
                # more code here
            # make sure it is looped once
            break
于 2015-09-08T08:10:49.573 に答える
4

一般的に言って、しないでください。「ifs」をネストしてそれらから抜け出す場合、それは間違っています。

ただし、次のことを行う必要がある場合:

if condition_a:
   def condition_a_fun():
       do_stuff()
       if we_wanna_escape:
           return
   condition_a_fun()
if condition_b:
   def condition_b_fun():
       do_more_stuff()
       if we_wanna_get_out_again:
           return
   condition_b_fun()

関数はifステートメントで宣言する必要はありません。事前に宣言することができます;)後で醜いif / thenをリファクタリングする必要がなくなるため、これはより良い選択です。

于 2010-01-15T06:55:35.393 に答える
4

関数の定義に依存しない別の方法があり(小さなコードスニペットでは読みにくい場合があるため)、余分な外側のwhileループを使用しません(一目で理解できるようにするには、コメントで特別な感謝が必要な場合があります) 、goto(...)を使用しません。最も重要なのは、ネストを開始する必要がない場合は、外側のインデントレベルを維持できるようにすることです。

if some_condition:
   ...
   if condition_a:
       # do something
       exit_if=True # and then exit the outer if block
if some condition and not exit_if: # if and only if exit_if wasn't set we want to execute the following code
   # keep doing something
   if condition_b:
       # do something
       exit_if=True # and then exit the outer if block
if some condition and not exit_if:
   # keep doing something

はい、それも読みやすさを再確認する必要がありますが、コードのスニペットが小さい場合は、繰り返されることのないwhileループを追跡する必要はなく、中間のifが何であるかを理解した後は、簡単に読み取ることができます。 1つの場所と同じインデント。

そして、それはかなり効率的であるはずです。

于 2018-11-07T08:24:13.473 に答える
1

事実上、あなたが説明しているのはgotoステートメントであり、これは一般的にかなり大きくパンされます。2番目の例ははるかに理解しやすいです。

ただし、クリーナーは次のようになります。

if some_condition:
   ...
   if condition_a:
       your_function1()
   else:
       your_function2()

...

def your_function2():
   if condition_b:
       # do something
       # and then exit the outer if block
   else:
       # more code here
于 2010-01-15T05:29:21.107 に答える
0

だからここで私はあなたがコードブロックの外側から抜け出そうとしていることを理解しています

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ブロックでfalse条件をテストして、コードブロックから暗黙的に終了することです。次に、elseブロックを使用して、他のifをネストして何かを実行します。

if test_for_false:
    # Exit the code(which is the outer if code)

else:
    if condition_a:
        # Do something

    if condition_b:
        # Do something
于 2018-05-31T12:23:44.713 に答える
0

これを処理する別の方法があります。単一のアイテムforループを使用して、続行を使用できるようにします。理由もなく余分な機能が不要になるのを防ぎます。さらに、潜在的な無限のwhileループを排除します。

if something:
    for _ in [0]:
        # Get x
        if not x:
            continue

        # Get y
        if not y:
            continue

        # Get z
        if not z:
            continue

        # Stuff that depends on x, y, and z
于 2020-04-15T18:18:18.237 に答える
0

追加のメソッドなしでこれを適用する唯一のものはelif、次の例のようになります

a = ['yearly', 'monthly', 'quartly', 'semiannual', 'monthly', 'quartly', 'semiannual', 'yearly']
# start the condition
if 'monthly' in b: 
    print('monthly') 
elif 'quartly' in b: 
    print('quartly') 
elif 'semiannual' in b: 
    print('semiannual') 
elif 'yearly' in b: 
    print('yearly') 
else: 
    print('final') 
于 2020-07-28T19:31:09.833 に答える
-2

if条件で使用するreturnと、関数から戻ります。そのため、returnを使用してif条件を解除できます。

于 2018-10-18T10:13:24.323 に答える