Home > Mobile >  I can't figure out what is wrong with this function?
I can't figure out what is wrong with this function?

Time:03-17

This is what it should return

Returns True if all items are truthy.

Examples:
>>> all_true([1, True, 'oregonstate'])
True
>>> all_true([0, 1, 2])
False
"""

This is what I have written

def all_true(items):
    for i in items:
        if i == True:
            return True
        else:
          return False
    pass

Not sure why it is not working, can someone help?

CodePudding user response:

Your function just returns the truthiness of the first item in the list, since it always returns on the first iteration.

You want to do something like this:

def all_true(items):
    for i in items:
        if not i:
            return False
    return True

Note that this all_true function already exists in Python. It is the the built-in all function.

CodePudding user response:

"All items are truthy" is logically equivalent to "no items are falsy."

def all_true(items):
    for i in items:
        if not i:
            return False
    return True

CodePudding user response:

Two problems. First, you are returning on the first True thing, when you should return when something is False. As stands, if any item is True, you return True. Second, if you want "truthy", don't compare specifically to True. foo == True is False. Instead, just let the if do the boolean test

def all_true(items):
    for i in items:
        if not i:
            return False
    return True

all and any are builtin functions that do the same thing. It would generally be preferable to use them.

  • Related