lind lind - 6 months ago 9
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)
print(cntrl())


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)

Answer

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:

print(coun(4)())
Comments