Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Nested Functions
#1
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
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020