Wednesday, June 4, 2008

Function call in Python

Check the following code:
def fibonacci(x):   
if x < 2: return 1
return (fibonacci(x-2) + fibonacci(x-1))

def factorial(x):
if x < 2: return 1
return (x * factorial(x-1))

def main():
funcs = [fibonacci, factorial]
n = 10
for i in range(len(funcs)):
print funcs[i](n)

main()

Interesting part of the code is print funcs[i](n). Sometimes it is useful to call the function in this way.

4 comments:

Paddy3118 said...

Hi,
That last for loop in main could be:

| for func in funcs:
| print func(n)

You can iterate over the list saving the complication of indexing.

- Paddy.

Paddy3118 said...

(Damn, it still ate my formatting)

subeen said...

Thanks. for func in funcs: is better definitely :)

Shiplu said...

This is something that most scripting/interpreted language supports. I used same thing in js and php. It can be used to build highly robust app.

how to know a language is scripting or even interpreted??
Ans: Check if it has any function like eval(). which dynamically executes code inside a string !!!