Home > Software design >  How does a "return" function end the execution of a Python script?
How does a "return" function end the execution of a Python script?

Time:09-27

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.

CodePudding user response:

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
    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 (five in total).

CodePudding user response:

the 'return False' statement will only execute after the for loop. But if you enter another return statement before that i won't get executed. Rule of thumb return statement ALWAYS exit functions.

CodePudding user response:

return stop the for and return True if a number can be divided by 7. I tried with has_lucky_number([14,16]) and returns me True

CodePudding user response:

The function end immediately after the first return statement.In this case,if the first number in the list is divisble by 7, the function will return True. If you want to see if all the numbers in the list are divisble by 7. You need to check them then return false or true at the end.

  • Related