Nice programing

여러 if와 elif의 차이점은 무엇입니까?

nicepro 2020. 12. 7. 20:41
반응형

여러 if와 elif의 차이점은 무엇입니까?


파이썬에서는 다음과 같은 차이점이 있습니까?

if text == 'sometext':
    print(text)
if text == 'nottext':
    print("notanytext")

 if text == 'sometext':
        print(text)
 elif text == 'nottext':
        print("notanytext")

다중 ifs가 원치 않는 문제를 일으킬 수 있는지 그리고 elifs 를 사용하는 것이 더 나은 방법인지 궁금합니다 .


다중 if는 코드가 모든 if 조건을 확인하고 elif의 경우와 같이 if 조건이 만족하면 다른 조건을 확인하지 않음을 의미합니다.


if와 elif 사용의 차이점을 확인하는 또 다른 쉬운 방법은 다음 예제입니다.

def analyzeAge( age ):
   if age < 21:
       print "You are a child"
   if age >= 21: #Greater than or equal to
       print "You are an adult"
   else:   #Handle all cases where 'age' is negative 
       print "The age must be a positive integer!"

analyzeAge( 18 )  #Calling the function
>You are a child
>The age must be a positive integer!

여기서 18을 입력으로 사용하면 답이 (놀랍게도) 2 문장임을 알 수 있습니다. 그건 틀렸어요. 첫 번째 문장이어야합니다.

둘 다 if 문이 평가되기 때문입니다. 컴퓨터는이를 두 가지 별도의 진술로 간주합니다.

  • 첫 번째는 18 세에 해당하므로 "You are a child"가 인쇄됩니다.
  • 두 번째 if 문은 거짓이므로 else 부분이 실행되고 "나이는 양의 정수 여야합니다"를 인쇄합니다.

ELIF의 수정이를 두를 만드는 경우 하나 문 '함께 스틱'

def analyzeAge( age ):
   if age < 21:
       print "You are a child"
   elif age > 21:
       print "You are an adult"
   else:   #Handle all cases where 'age' is negative 
       print "The age must be a positive integer!"

analyzeAge( 18 )  #Calling the function
>You are a child

편집 : 맞춤법 수정


def multipleif(text):
    if text == 'sometext':
        print(text)
    if text == 'nottext':
        print("notanytext")

def eliftest(text):
    if text == 'sometext':
        print(text)
    elif text == 'nottext':
        print("notanytext")

text = "sometext"

timeit multipleif(text)
100000 loops, best of 3: 5.22 us per loop

timeit eliftest(text)
100000 loops, best of 3: 5.13 us per loop

elif가 약간 더 빠르다는 것을 알 수 있습니다. 더 많은 ifs와 더 많은 elifs가 있으면 더 분명해질 것입니다.


이에 대해 다른 생각 방법이 있습니다.

if / else catchall 구조로 충분하지 않은 두 가지 특정 조건이 있다고 가정 해 보겠습니다.

예:

3 X 3 tic-tac-toe 보드가 있고 나머지 사각형이 아닌 두 대각선의 좌표를 인쇄하고 싶습니다.

Tic-Tac-Toe 좌표계

대신 if / elif 구조를 사용하기로 결정했습니다.

for row in range(3):
    for col in range(3):
        if row == col:
            print('diagonal1', '(%s, %s)' % (i, j))
        elif col == 2 - row:
            print('\t' * 6 + 'diagonal2', '(%s, %s)' % (i, j))

출력은 다음과 같습니다.

diagonal1 (0, 0)
                        diagonal2 (0, 2)
diagonal1 (1, 1)
                        diagonal2 (2, 0)
diagonal1 (2, 2)

하지만 기다려! (1, 1)도 대각선 2의 일부이기 때문에 대각선 2의 세 좌표를 모두 포함하고 싶었습니다.

The 'elif' caused a dependency with the 'if' so that if the original 'if' was satisfied the 'elif' will not initiate even if the 'elif' logic satisfied the condition as well.

Let's change the second 'elif' to an 'if' instead.

for row in range(3):
    for col in range(3):
        if row == col:
            print('diagonal1', '(%s, %s)' % (i, j))
        if col == 2 - row:
            print('\t' * 6 + 'diagonal2', '(%s, %s)' % (i, j))

I now get the output that I wanted because the two 'if' statements are mutually exclusive.

diagonal1 (0, 0)
                        diagonal2 (0, 2)
diagonal1 (1, 1)
                        diagonal2 (1, 1)
                        diagonal2 (2, 0)
diagonal1 (2, 2)

Ultimately knowing what kind or result you want to achieve will determine what type of conditional relationship/structure you code.


In your above example there are differences, because your second code has indented the elif, it would be actually inside the if block, and is a syntactically and logically incorrect in this example.

Python uses line indentions to define code blocks (most C like languages use {} to enclose a block of code, but python uses line indentions), so when you are coding, you should consider the indentions seriously.

your sample 1:

if text == 'sometext':
    print(text)
elif text == 'nottext':
    print("notanytext")

both if and elif are indented the same, so they are related to the same logic. your second example:

if text == 'sometext':
    print(text)
    elif text == 'nottext':
        print("notanytext")

elif is indented more than if, before another block encloses it, so it is considered inside the if block. and since inside the if there is no other nested if, the elif is being considered as a syntax error by Python interpreter.


elifis just a fancy way of expressing else: if,

Multiple ifs execute multiple branches after testing, while the elifs are mutually exclusivly, execute acutally one branch after testing.

Take user2333594's examples

    def analyzeAge( age ):
       if age < 21:
           print "You are a child"
       elif age > 21:
           print "You are an adult"
       else:   #Handle all cases were 'age' is negative 
           print "The age must be a positive integer!"

could be rephrased as:

    def analyzeAge( age ):
       if age < 21:
           print "You are a child"
       else:
             if age > 21:
                 print "You are an adult"
             else:   #Handle all cases were 'age' is negative 
                 print "The age must be a positive integer!"

The other example could be :

def analyzeAge( age ):
       if age < 21:
           print "You are a child"
       else: pass #the if end
       if age > 21:
           print "You are an adult"
       else:   #Handle all cases were 'age' is negative 
           print "The age must be a positive integer!"

When you use multiple if, your code will go back in every if statement to check the whether the expression suits your condition. Sometimes, there are instances of sending many results for a single expression which you will not even expect. But using elif terminates the process when the expression suits any of your condition.


Here's how I break down control flow statements:


# if: unaffected by preceding control statements
def if_example():
    if True:
        print('hey')
    if True:
        print('hi')  # will execute *even* if previous statements execute

will print hey and hi


# elif: affected by preceding control statements
def elif_example():
    if False:
        print('hey')
    elif True:
        print('hi')  # will execute *only* if previous statement *do not*

will print hi only because the preceding statement evaluated to False


# else: affected by preceding control statements
def else_example():
    if False:
        print('hey')
    elif False:
        print('hi')
    else:
        print('hello')  # will execute *only* if *all* previous statements *do not*

앞의 모든 명령문이 실행되지 hello않았기 때문에 인쇄됩니다.

참고 URL : https://stackoverflow.com/questions/9271712/difference-between-multiple-ifs-and-elifs

반응형