jeudi 4 juin 2020

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)

Aucun commentaire:

Enregistrer un commentaire