Nested Functions - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Nested Functions (/thread-11159.html) |
Nested Functions - aditvaddi - Jun-26-2018 a,b,c = 5,2,3 def f(a): def g(b): def h(c): return a*b*c return h return g print(g) f(a)I'm trying to created nested functions such that the function f includes a print function and when we execute f(a), it prints 30. but this doesn't happen here. Help please! I know that if i put the print outside the f function and run it as print(f(a)(b)©), it gives the result as 30 too RE: Nested Functions - ichabod801 - Jun-26-2018 g returns h, which is the function h itself, not a call to the function. That's fine, that's the way you usually do it. But when you print(g), you are printing the function g itself, not the result of a call to g. That's why you need to do f(a)(b)(c) . Let's step through it: f(a) returns g, so you get g(b)(c) . g(b) returns h, so you get h(c) , which returns 30.You are using a, b, and c both globally and inside the function h. But the a, b, and c in h and not the global a, b, and c that you have defined globally. They are the a, b, and c that you set as parameters in the def statements, and they are whatever is passed to the function. That means that f(1)(2)(3) will give you 6. I don't know if that's what you're expecting.
|