programing

if 절을 종료하는 방법

elecom 2023. 7. 17. 20:39
반응형

if 절을 종료하는 방법

조기 종료를 위한 방법은 무엇입니까?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

이를 위한 한 가지 방법을 생각할 수 있습니다. 문이 중첩된 경우 종료 사례가 발생한다고 가정하면 나머지 코드를 다른 큰 블록으로 묶습니다.예:

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루프 및수 기타 , 다중중루첩및프사할기없구타조break쉽게부터

  1. 코드를 자체 기능으로 래핑합니다.
  2. 에 에.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()
    ...
이동에서 가져오기로 이동, 레이블
if some_condition:
...if condition_a:
을 하다, 을 보다그런 다음 외부 if 블록을 종료합니다.끝까지 가다, 끝까지 가다, 끝까지...if condition_b:
을 하다, 을 보다그런 다음 외부 if 블록을 종료합니다.끝까지 가다, 끝까지 가다, 끝까지여기에 더 많은 코드
레이블 .end

(이것을 실제로 사용하지 마십시오.)

while some_condition:
   ...
   if condition_a:
       # do something
       break
   ...
   if condition_b:
       # do something
       break
   # more code here
   break

다음과 같은 예외를 사용하여 goto의 기능을 에뮬레이트할 수 있습니다.

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

고지 사항:저는 단지 당신에게 이런 식으로 일을 할 수 있는 가능성을 알려주려는 것일 뿐, 일반적인 상황에서는 결코 그것을 합리적인 것으로 인정하지 않습니다.질문에 대한 코멘트에서 언급했듯이, 애초에 비잔틴 조건을 피하도록 코드를 구조화하는 것이 훨씬 선호됩니다. :-)

이것일까요?

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

실제로 요청받은 것에 대해, 제 접근 방식은 그것들을 넣는 것입니다.ifs 원 루프 내의

for _ in range(1):
    if (some_condition):
        # do something applicable to all condition
        ...
        if (condition_a):
            # do something
            # and then exit the outer if block
            break
        # do something applicable to some_condition but not for condition_a 
        ...
        if (condition_b):
            # do something
            # and then exit the outer if block
            break
        # do something applicable to some_condition but neither for condition_a/b
        ...

다음의 조합을 사용하는 대신 이 기능을 사용합니다.elif & andDRY(반복하지 않음) 코드를 작성하는 데 도움이 됩니다.사중인경우를 .elif & and를 다시 써야 할 수도 있습니다.# do something applicable to all condition또는 다른 라인을 여러 번 표시합니다.회선이 단순한 함수 호출일지라도 덜 깨끗합니다.

테스트:

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

일반적으로 말하면, 하지 마세요.만약 여러분이 "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 문에서 선언할 필요가 없으며, 미리 선언할 수 있습니다.;) 나중에 추악한 경우 재팩터링할 필요가 없기 때문에 이 방법이 더 나은 선택이 될 수 있습니다.

함수 정의에 의존하지 않는 또 다른 방법이 있습니다(가끔 작은 코드 스니펫에 대해 덜 읽기 때문에). 루프를 추가로 사용하지 않는 반면(첫 눈에 이해할 수 있도록 댓글에 특별한 감사가 필요할 수도 있음), 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

네, 하지만 코드 조각이 작으면 반복되지 않는 루프를 추적할 필요가 없습니다. 중간이 무엇을 위한 것인지 이해한 후에는 모두 한 곳에서 동일한 들여쓰기로 쉽게 읽을 수 있습니다.

그리고 그것은 꽤 효율적이어야 합니다.

이것을 다루는 또 다른 방법이 있습니다.계속을 사용할 수 있는 단일 항목을 루프에 사용합니다.그것은 이유 없이 추가 기능을 가질 필요가 없는 것을 방지합니다.또한 무한대의 잠재력을 제거하는 동시에 루프가 발생합니다.

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

사실상 당신이 설명하는 것은 일반적으로 상당히 많이 판을 친 진술로 이동하는 것입니다.당신의 두 번째 예는 훨씬 더 이해하기 쉽습니다.

그러나 청소기는 여전히 다음과 같습니다.

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

그래서 여기서 코드 블록이 외부에서 탈출하려고 하는 것을 이해합니다.

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

한 가지 방법은 외부 if 블록에서 잘못된 조건을 테스트하여 코드 블록 밖으로 암시적으로 빠져나간 다음 다른 블록을 사용하여 다른 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

없이 할 수 은 추적인방없이이적것용수은입니다.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') 

여러 가지 방법이 있습니다.코드가 어떻게 구현되는지에 따라 다릅니다.

는 함를종는경다사음용다니합을우하료를 사용합니다.return다음 이후에는 코드가 실행되지 않습니다.return은 예제 그러면 예제 코드는 다음과 같습니다.

def func1(a):
    if a > 100:
        # some code, what you want to do
        return a*a 
    if a < 100:
         # some code, what you want to do
        return a-50
    if a == 100:
         # some code, what you want to do
        return a+a

루를종경우할을 합니다.break다음 이후에는 코드가 실행되지 않습니다.break키워드그러면 예제 코드는 다음과 같습니다.while그리고.for루프:

a = 1
while (True):
    if (a == 10):
        # some code, what you want to do
        break
    else:
        a=a+1
        print("I am number", a)

for i in range(5):
    if i == 3:
        break
    print(i)

기본 조건을 종료한 경우 다음을 사용할 수 있습니다.exit()직접 지휘하다그런 다음 코드를 입력합니다.exit()명령이 실행되지 않습니다.

NB: 이런 유형의 코드는 선호되지 않습니다.이것 대신 기능을 사용할 수 있습니다.예를 들어 코드를 공유할 뿐입니다.

예제 코드는 다음과 같습니다.

if '3K' in FILE_NAME:
        print("This is MODIS 3KM file")
        SDS_NAME = "Optical_Depth_Land_And_Ocean"
        
    elif 'L2' in FILE_NAME:
        print("This is MODIS 10KM file")
        SDS_NAME = "AOD_550_Dark_Target_Deep_Blue_Combined" 
        exit()
    else:
        print("It is not valid MODIS file")

제가 훑어봤는데 아무도 이 기술에 대해 언급하지 않았습니다.이는 다른 솔루션에 비해 간단하며, 예외 시도 문을 사용하지 않으려는 경우 이 방법이 최선의 방법일 수 있습니다.

#!/usr/bin/python3
import sys

foo = 56

if (foo != 67):
    print("ERROR: Invalid value for foo")
    sys.exit(1)

사용하다returnin if 조건은 함수에서 사용자를 반환하므로 반환을 사용하여 if 조건을 해제할 수 있습니다.

언급URL : https://stackoverflow.com/questions/2069662/how-to-exit-an-if-clause

반응형