lind lind - 9 months ago 24
Python Question

why are assigning functions to identifiers necessary while invoking them?

I'd like to take an example code for this:

def coun(n):
count = 0
def counter():
nonlocal count
if count < n:
count += 1
return count
return counter

cntrl = coun(4)

why must we assign the function to an identifier, further more in the print statement, the cntrl is invoked using parenthesis, and in the return statement of the function coun the counter is not returned using parenthesis. What is this?(I'm just a novice at python)


It's not

Because you are doing return counter rather than return counter() you are returning a function rather than the result of that function, in order to get the result you need to call this function. You can do this, as you have done, by assigning it to a variable or you can call it immediately with the usual function call convention: