user9135852
user9135852

Reputation: 51

Return true doesn't work but return false does

How come

def allEven(n):
    for c in n:
            if c % 2 != 0:
                    return False
    return True

works but

def allEven(n):
    for c in n:
            if c % 2 == 0:
                    return True
    return False

doesn't? With the second one, when I type allEven([8, 0, -1, 4, -6, 10]), it says it's True.

Upvotes: 0

Views: 747

Answers (2)

Artier
Artier

Reputation: 1673

Return Statement terminate loop and end program. If c % 2 == 0 is True, it Return True and terminate program not check all values.

Try This

def allEven(n):
    for c in n:
        if c % 2 == 0:
            continue
        else:
            return False
    return True

Upvotes: 1

pjpj
pjpj

Reputation: 441

In your second method, you return True once you find an even c in n which is not what your method supposed to do: return true IFF all cs are even.

Upvotes: 5

Related Questions