DWCY
DWCY

Reputation: 41

Cannot get True when finding a number in a list that is divisible by 7

def divisible_by_7(lst: List[int]) -> bool:
    """Return True if and only if lst contains an element divisible
    by 7. Otherwise, return False.

    >>> divisible_by_7([4,8,21,6])
    True
    >>> divisible_by_7([1,2,8,9])
    False
    """
    for num in lst:
        if num % 7 == 0:
            return True
        elif num % 7 !=0:
           return False

I keep on getting false even if the answer is true. I know that if we return false it won't work because when the function looks through the list, if there is even one instance where there is a number that isn't divisible by 7, it fails. How do I correct this?

Upvotes: 1

Views: 2309

Answers (2)

user2390182
user2390182

Reputation: 73480

You are returning from the first iteration. The comments and Oleg Butuzov's answer have you covered there. However, the built-in shortcut for this pattern would be any:

def divisible_by_7(lst):
    return any(x % 7 == 0 for x in lst)

Upvotes: 1

Oleg Butuzov
Oleg Butuzov

Reputation: 5405

How about to iterate thought all list elements?

def divisible_by_7(my_list):
    for num in my_list:
        if num % 7 == 0: 
            return True;
    return False;

Upvotes: 1

Related Questions