Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
nested function return
#3
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".
Reply


Messages In This Thread
nested function return - by MHGhonaim - Oct-01-2023, 11:31 PM
RE: nested function return - by menator01 - Oct-01-2023, 11:56 PM
RE: nested function return - by deanhystad - Oct-02-2023, 09:21 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  return next item each time a function is executed User3000 19 2,383 Aug-06-2023, 02:29 PM
Last Post: deanhystad
  function return boolean based on GPIO pin reading caslor 2 1,225 Feb-04-2023, 12:30 PM
Last Post: caslor
  return vs. print in nested function example Mark17 4 1,800 Jan-04-2022, 06:02 PM
Last Post: jefsummers
  Exit function from nested function based on user input Turtle 5 2,970 Oct-10-2021, 12:55 AM
Last Post: Turtle
  How to invoke a function with return statement in list comprehension? maiya 4 2,919 Jul-17-2021, 04:30 PM
Last Post: maiya
  Function - Return multiple values tester_V 10 4,566 Jun-02-2021, 05:34 AM
Last Post: tester_V
Question Stopping a parent function from a nested function? wallgraffiti 1 3,712 May-02-2021, 12:21 PM
Last Post: Gribouillis
  Get return value from a threaded function Reverend_Jim 3 17,273 Mar-12-2021, 03:44 AM
Last Post: Reverend_Jim
  Return not exiting function?? rudihammad 3 5,361 Dec-01-2020, 07:11 PM
Last Post: bowlofred
  Why does my function return None? vg100h 3 2,249 Oct-29-2020, 06:17 AM
Last Post: vg100h

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020