I am told that the following python-code does return me a true/false statement wether at least one element of the list "nums" is divisible by 7 (yeah, and for a 0). But let’s say that the first value in the list is 14, so clearly divisible by 7.
I then would expect a return of "true" due to the "for" loop. And then the script continues and gives me the return "false", no matter what happend before that? Or does the skript abort after it finds a "true"? I thought I really understood how "return" works in python, but apparently not.
def has_lucky_number(nums):
"""Return whether the given list of numbers is lucky. A lucky list contains
at least one number divisible by 7.
"""
for num in nums:
if num % 7 == 0:
return True
return False
I would be very gratefull for some help here.
EDIT: apparently this seems to be unclear: I want to know WHY this skript returns "True" if nums has an element [14]. I know that it does that. But I would not expect it to do that because I would expect the last thing the code does to be to always return "False" due to the last line.
>Solution :
In most languages ‘return’ means you return a value and exit the function to the callee.
If you want it to "return" multiple values, essentially you want it to either return a list, or you want the function to be a generator.
A generator is something that yields rather than returns multiple values. So in your example you could instead do something like this:
def has_lucky_number(nums):
"""Return whether the given list of numbers is lucky. A lucky list contains
at least one number divisible by 7.
"""
for num in nums:
if num % 7 == 0:
yield True
else:
yield False
Which you would then use like this:
for value in has_lucky_number([1,2,5,14]):
# do something
Which would yield multiple values (four in total).