Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does a "return" function end the execution of a Python script?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading