Python Forum

Full Version: nested function return
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
in which cases is it need to add () to inner functions return and why is it different in the following 2 examples
[Image: 0m41mjL]
[Image: F3C2VM9]
Please post code and not images of code.
Quote: why is it different in the following 2 examples
Because they do completely different things?

The modulo division example uses an inner function for code reuse. There is some code that is repeated three times (x % 2 + 5). Instead of repeating the same code 3 times, it was placed in a function and called 3 times. This looks silly in that particular example, but imagine if the reused code was 10 lines instead of 1 and it looks less silly.

If the amount of code in the inner function is much greater than 10 lines it might make more sense to make the inner function an outer function.
def inner(x):
    return x % 2 + 5

def mod2plus5(x1, x2, x3)
    return inner(x1), inner(x2), inner(x3)
The echo example uses an inner function to create a closure. Here the inner function does all the work, and the outer function's only job is to assign a value to n. The inner function and the variable n create a closure. When you call twice(), inner remembers that n == 2. When you call thrice(), inner remembers n == 3.

Making the inner function an outer function is not an option in the echo example. The echo example needs the inner() function to run inside a scope where "n" is defined. Moving inner() outside echo(n) moves inner() to a new scope where there is no enclosed variable "n".