Home > Software design >  difference between controlling the flow with if and elif
difference between controlling the flow with if and elif

Time:12-26

i was running a program that return the maximum 2 number in a certain list

and I found that there a difference between using if and elif in definition of function

So if i used :


def maxi (lst) :
    max_pos1 = 0 
    max_pos2 = 1 
    if lst[max_pos1] < lst [max_pos2] :
        max_pos1 , max_pos2 = 1 , 0 
    for x in range (len(lst)) :
        if lst[max_pos1] < lst [x] :
            max_pos1 , max_pos2 = x , max_pos1 
        if lst [max_pos2] < lst [x] :
            max_pos2 = x 
    return lst[max_pos1] , lst[max_pos2]



lst = [1,2,3,4,5,6,7,8,9,10,11,12,77,14,15,16]

print(maxi(lst))


the output will be :

(77, 77)

Which is not correct in my opinion

but if i changed if in the 9 line to elif as follow :



def maxi (lst) :
    max_pos1 = 0 
    max_pos2 = 1 
    if lst[max_pos1] < lst [max_pos2] :
        max_pos1 , max_pos2 = 1 , 0 
    for x in range (len(lst)) :
        if lst[max_pos1] < lst [x] :
            max_pos1 , max_pos2 = x , max_pos1 
        elif lst [max_pos2] < lst [x] :
            max_pos2 = x 
    return lst[max_pos1] , lst[max_pos2]



lst = [1,2,3,4,5,6,7,8,9,10,11,12,77,14,15,16]

print(maxi(lst))


the output will be :

(77, 16)

which the result i hoped for , can any one explain why this change happened in the output ?

CodePudding user response:

if ...elif...else is one control flow, only one condition in this flow will satisfy and data can be changes

if ..elif..else and then if ..elif ..else, are two different control flow and 2 condition change will hapen

in first code case, it is 2 control flow, in second one only 1 control flow

CodePudding user response:

Yes, that makes sense. If you have two if statements both will execute regardless if the first condition was met or not. If you use if followed by elif the elif statement will only be checked if the first if condition was not met.

  • Related