assigning a variable to a function | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

assigning a variable to a function

Hello something that I do not understand def foo(): def bar(): print(spam) spam = 'ham' bar() spam = 'eggs' bar() return bar b = foo() b() On this configuration, the output will be ham eggs eggs Why b= foo() and b() are not producing the same output ? I encounter this several time and I cannot understand.

4th Jul 2020, 6:42 AM
nicolas seespan
nicolas seespan - avatar
3 Answers
+ 1
First of, you didn't have to assign it to a variable. You could have just did: foo() If you did assign it in a variable (like you did), I think it'd produce the last result. This much I know. The same way: for x in range(5): pass print(x) Output would be 4 as it was iterated last. I await a better answer though...😃😃😃
4th Jul 2020, 12:25 PM
Tomiwa Joseph
Tomiwa Joseph - avatar
0
def foo(): def bar(): print(spam) spam = 'ham' bar() spam = 'eggs' bar() return bar print("result of foo(): \n") foo() print("\nresult of b():\n ") """do not use b = foo() with brackets. Instead use it as follows and it yields the same result!""" b = foo b()
4th Jul 2020, 12:15 PM
yyy
0
So I found the answer. When you do : b = foo() you return the function bar and assign it to b. You have an enclosure with "spam" and its last value is "eggs" So b() is equivalent to bar(), but you could not write bar() only because it is inside foo() .
5th Jul 2020, 7:29 AM
nicolas seespan
nicolas seespan - avatar