jeudi 4 octobre 2018

Else condition always works

There is a bug in my code which i'm not able to identify. This code should return True if the list contains [3,3] in it.

But, if i write an else condition, it always shows False. If i skip the else condition, the code works fine.

def has_33(nums):
    for i in range(0,len(nums)-1):
        if nums[i]==3 and nums[i+1]==3:
            return True
        else:
            return False
    pass

The above code returns :

# Check
has_33([1, 3, 3]) . -- > False

# Check
has_33([1, 3, 1, 3]) --> False.

But, if i change the code to this :

def has_33(nums):
    for i in range(0,len(nums)-1):
        if nums[i]==3 and nums[i+1]==3:
            return True
    pass

The code works fine :

# Check
has_33([1, 3, 3]) --> True

# Check
has_33([1, 3, 1, 3]) -- > Returns nothing , False.

Why is this happening ?

Can someone help me out ?

Thank you.

Aucun commentaire:

Enregistrer un commentaire