Reputation: 81
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
return False
When I run this function, it will only execute once. How can I instead verify all values in the list and see if they are True or False so it properly follows how for
loops function without using the built-in any
function?
Upvotes: 0
Views: 1962
Reputation: 4315
Use for-else
loop
Ex.
def divisible_by_7(lst: list) -> bool:
for num in lst:
if num % 7 == 0:
return True
else:
return False
lst = [4,8,21,6]
lst1 = [1,2,8,9]
print(divisible_by_7(lst))
print(divisible_by_7(lst1))
True
False
Upvotes: 1
Reputation: 21
def divisible_by_7(self, lst):
"""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
return False
Put your return False statement outside of the for-loop. Return True iff there is an element in the list that is divisible by 7 and return False as default.
Upvotes: 2
Reputation: 2137
Since there is no if check for return False
if it grabs no if num % 7 == 0
it returns False in any iteration, you should dedent return False
as @jonrsharpe commented. Yet, you can have the following code.
Code
def divisible_by_7(lst: list) -> 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
"""
return any([num%7 == 0 for num in lst])
Output
>>> divisible_by_7([4,8,21,6])
True
>>> divisible_by_7([1,2,8,9])
False
Upvotes: 1