dimanche 15 mars 2020

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?

Aucun commentaire:

Enregistrer un commentaire