Can a function be called within a function ?

P

Peter Moscatt

Is it possible to write code and allow a function to be called within
another like I have shown below ?

Pete



def populatelist():
f=open(_globals.appath + "dxcluster.svr","r")
while true:
text = f.readline()
if text =="":
break
_list.append(string.strip(text))
f.close()


def serversettings():
servers.main(root)
if _globals.refresh=="yes":
populatelist() <----------------------- calling function above.
 
T

Tim N. van der Leeuw

Hiya,

That's certainly possible, it's standard practice.

(It might be cleaner to pass filenames using parameters though)

cheers,

--Tim
 
K

Kent Johnson

Peter said:
Is it possible to write code and allow a function to be called within
another like I have shown below ?

Yes, of course. In fact you do it six times in the code below, to call open(), readline(), append(),
close(), main() and populatelist().

Kent
 
S

Steve Horsley

Peter said:
Is it possible to write code and allow a function to be called within
another like I have shown below ?

Pete



def populatelist():
f=open(_globals.appath + "dxcluster.svr","r")
while true:
text = f.readline()
if text =="":
break
_list.append(string.strip(text))
f.close()


def serversettings():
servers.main(root)
if _globals.refresh=="yes":
populatelist() <----------------------- calling function above.

Yes. It is perfectly normal. As programs get more complex, you
find methods calling methods calling methods. And as Kent pointed
out, you are already callin methods from withon methods by
calling the likes of open() and close().

Beware of creating loops - methods that call themselves, eitehr
directly or by calling other methods that end up calling the
original method. This can be done with care to make sure that at
some point a method is sure to return without calling onwards,
usually by having the problem simplified every time, but you
should avoid this kind of thing for now. It's called recursion.
An example would be in calculating x to the power of y. x^y can
be calculated by working out x * x^(y-1), but x^(y-1) is x *
x^(y-2) etc. But you canbe sure this ends when we finally come to
work out x^1 which is x, and this breaks the loop. If that makes
sense.

Steve
 
P

Peter Moscatt

Thanks Guys,

I didn't think it was calling the function so I will put some test code and
print something to the screen just to ensure it's entering the function.

Thanks for all ya help.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top