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.

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)
Tamim Shahriar 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 !!!
MARK said…
can you help me,,,
i'm a new in python,,,
my problem is, can you give a simple codes in inputting first the positive integer then output the factorial of the inputted numbers...
Unknown said…
Hi,
Can you tell me what's wrong with this:

class xyz:
def fibonacci(self, x):
if x < 2: return 1
return (self.fibonacci(x-2) + self.fibonacci(x-1))

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

funcs = [fibonacci, factorial]
def w(self):
return self.funcs

if __name__ == "__main__":
funcs2 = xyz().w()
n = 10
for i in range(len(funcs2)):
print xyz().funcs2(n)

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code