-1

Running the code below prints hellohello hellohellohello However, I never specified a parameter to either twice variable or thrice variable. Also, I never assigned 'hello' to word1. How does it return the answer then? How can twice or thrice take in a parameter and equate it to word1?

def echo(n):
    """Return the inner_echo function."""

    def inner_echo(word1):
        """Concatenate n copies of word1."""
        echo_word = word1 * n
        return echo_word

    return inner_echo

twice = echo(2)
thrice = echo(3)

print(twice('hello'), thrice('hello'))
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Hamza Khalid
  • 221
  • 3
  • 12
  • 5
    *"I never specified a parameter to either twice variable or thrice variable"* - yes you did. *"I never assigned hello to word1"* - yes you did. Key words: "higher order functions". – jonrsharpe Mar 26 '20 at 22:47
  • Does this answer your question? [Why aren't python nested functions called closures?](https://stackoverflow.com/questions/4020419/why-arent-python-nested-functions-called-closures) – DarioHett Mar 26 '20 at 22:49
  • 1
    `echo` returns `inner_echo` which is a function that accepts an argument. You are calling `echo` and assign its return value to `twice` and `thrice`. Thus `twice` and `thrice` are functions that accept an argument. – Felix Kling Mar 26 '20 at 22:50
  • I understand that I assigned parameters to twice and thrice. But how can those parameters be then equated to word1. I don't get it still – Hamza Khalid Mar 26 '20 at 23:08
  • https://stackoverflow.com/a/12423750/2823755 – wwii Mar 26 '20 at 23:55
  • https://stackoverflow.com/questions/2005956/how-do-nested-functions-work-in-python – wwii Mar 26 '20 at 23:57

1 Answers1

1

Look at your last line of code, print(twice('hello'), thrice('hello')). When you declared twice and thrice as your functions (twice = echo(2) thrice = echo(3)), you are actually specifying word1 as hello.

hoop_coop
  • 23
  • 5
  • word1 is the parameter for inner_echo(). How can parameters for twice or thrice be equated to parameters for inner_echo()? I'm still not able to understand – Hamza Khalid Mar 26 '20 at 23:06
  • So what you did is you placed the inner_echo() function inside of echo(n). Then you did twice = echo(n). Which means when you call twice you are actually calling echo(n). – hoop_coop Mar 26 '20 at 23:16
  • I understand when I call twice I call echo(n). When echo(n) is called it in turn calls inner_echo(word1). My confusion is where/how is it specified that word1 is equal to 'hello' – Hamza Khalid Mar 26 '20 at 23:22
  • Inside echo(n) is inner_word(word1), When you write twice = echo(2). You have specified that parameter. So now when you call twice('hello'), you are actually calling twice(word1). You have put it inside your echo. – hoop_coop Mar 26 '20 at 23:33