I'm trying to understand how Python processes the code in the examples below:
When cake()() is executed, Python first prints 'beets' then prints 'sweets'
However, when chocolate() is executed, Python only prints 'sweets'
Could someone explain the difference for the 2 scenarios?
Also when more_chocolate is executed, Python does not print any values, it simply returns 'cake'.
I'm sure there's a tidy explanation for these cases. Hope someone can explain!
def cake():
print('beets')
def pie():
print('sweets')
return 'cake'
return pie
chocolate = cake()
cake()()
chocolate()
more_chocolate, more_cake = chocolate(), cake
more_chocolate
When you execute
cake(), the following chunk is run:So it:
beetspiefunction definition, the function body is not run yet hence no printing ofsweetspiefunction objectYou're saving the returned function object as name
chocolate, so it now refers to thepiefunction object.So when you execute
chocolate(), it actually runspie()now and does the following:sweetscakeWhen you do
cake()()it also does the same thing without using the intermediate variablechocolate. Socake()()runs the returned function object fromcake()i.e.piewith the prints.