Can a function be called within a function ?

Steve Horsley steve.horsley at gmail.com
Mon Apr 18 16:21:36 EDT 2005


Peter Moscatt wrote:
> 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



More information about the Python-list mailing list