lundi 1 mai 2017

python if/else logic explained please

I have a really basic if/else logic question for Python. An exercise in the book required me to write a function that takes a list of integers are returns True if the list contains all even numbers and False if it doesn't.

I wrote:

list1 = [8,0,-2,4,-6,10]
list2 = [8,0,-1,4,-6,10]
def allEven(list):
    for x in list:
        if x % 2 != 0:
            return False
        else:
            return True

This code always returns True. Why is that? Doesn't the code see the -1 during the loop of all the values of the list and returns the False?

list1 = [8,0,-2,4,-6,10]
list2 = [8,0,-1,4,-6,10]
def allEven(list):
    for x in list:
        if x % 2 != 0:
            return False
    return True

The book gives the answer of this. Why does this work and mine doesn't?

Aucun commentaire:

Enregistrer un commentaire