Michael Wells
Michael Wells

Reputation: 37

Behavioural difference of if-if-else and if-elif-else in a while loop

I am unable to get my desired output when 'if-if-else' conditioning is used. However, using 'if-elif-else' works just fine. I have tried tracing but do not understand the reason for the difference in outputs. I am unsure why does it break out after just 1 execution for the 'if-if-else' case and why doesn't it perform like when 'if-elif' is used.

Here are the codes: they are exactly the same except 'if' is replaced with 'elif' on line 8

1.if-if-else

x = 1                                                
y = 0
while True:
    if (x is not None ) & (y%30!=0):
       y+=1
       x=5
       print("x=",x)
    if y%30==0:               #line8
       print("ENTERED y=",y)
       y-=29
    else:
       break

2.if-elif-else

x = 1
y = 0
while True:
    if (x is not None ) & (y%30!=0):
        y+=1
        x=5
        print("x=",x)
    elif y%30==0:              #line8
        print("ENTERED y=",y)
        y-=29
    else:
        break

Here are the outputs:

1.if-if-else

       ENTERED y= 0
       x= 5

2.if-elif-else

       ENTERED y= 0
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       x= 5
       ENTERED y= 0
       x= 5
       x= 5
       x= 5
       x= 5
       ...(prints x=5 for another 29-4 =25 times)
       ENTERED y= 0
       ...(loops endlessly)

Upvotes: 0

Views: 83

Answers (1)

snatchysquid
snatchysquid

Reputation: 1352

Of course there's a difference! elif stands for else if. When having another if after an if the second if will be checked regardless of the result you got from the first if.

When having an else or an else if (the key point is the else) the statement will be checked only if the first if condition turned out to be False.

Please note that when using the if alone in line 8 then the following else is "connected" to that second if, but when using elif all of the elses and ifs are "the same block". So in the second case since always it's either y % 30 == 0 or y % 30 != 0 (and x is not None) it will never reach the break!

Upvotes: 1

Related Questions