Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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].

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?

like image 641
Megha_991 Avatar asked Dec 24 '22 03:12

Megha_991


1 Answers

It's because the else condition is satisfied first. You have a for loop which goes over all the numbers in your list [1,3,3], first it check's the first number which is 1 and then the second number which is 3;

if nums[i]==3 and nums[i+1]==3:

In this case nums[i] is 1 which means nums[i]==3 is not True , which means your code will go straight to the Else

And the solution to your problem is simple:

def has_33(nums):
    for i in range(len(nums)):
        if nums[i]==3 and nums[i+1]==3:return True
    return False
like image 171
HaR Avatar answered Dec 25 '22 17:12

HaR