pythonif-statementscopenested

I get an error when I end the if statement with a concluding else statement


I wrote this Python code that would check a list and return True if two items in the list next to each other are of the same value:

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

Result 1:

>>> samer([1,3,44,5,5,8])
False

This is where I'm puzzled because I feel it should return True.

Result 2:

>>> samer([3,3,49,93,5,8])
True

It only returns True if the first and second number in the list is True.

The solution:

def samer(nums):
    for i in range(0,len(nums)-1): 
        if (nums[i]) == (nums[i+1]):
            return True
    return False

The above code works well, so my question is since the else statement indented under the if condition's purpose is to return False if no number in the list is next to each other in the process of the for loop, why do I still get False in Result 1?

Is it that it doesn't loop again after checking the first two boxes and why is that since it's the purpose of the for loop to go over each iteration and then check for the conditions?


Solution

  • When a function returns, that's it. The function is done, over, finished..

    Since you're returning either true or false when checking each and every element, you really only check the first time through the loop (elements one and two), as you observe.

    You should return true if a match is found and only return false at the end, when you've checked everything and, therefore, no matches are found. That code is already in your question, the bit under The solution.