Reputation: 67
def f1(x,y):
return x+y
def f2(x,y):
return x-y
def f3(x,y):
return x//y
def f4(x,y):
return x*y
def f5(x,y):
return x**y
def f6(x,y):
return x%y
def f7(x,y):
return y-x
def f8(x,y):
return y//x
def f9(x,y):
return y%x
def f10(x,y):
return y**x
funcs=[f1,f2,f3,f4,f5,f6,f7,f8,f9,f10]
for i in funcs:
print(i)
num=eval(input('Enter a number: '))
funcs[i]((3,5))
I know that the issue is with the declaration of i
since i get this error message when I run the code:
<function f1 at 0x7f700458de18>
<function f2 at 0x7f7002ee7620>
<function f3 at 0x7f7002ee78c8>
<function f4 at 0x7f7002ee7950>
<function f5 at 0x7f7002ee79d8>
<function f6 at 0x7f7002ee7a60>
<function f7 at 0x7f7002ee7ae8>
<function f8 at 0x7f7002ee7b70>
<function f9 at 0x7f7002ee7bf8>
<function f10 at 0x7f7002ee7c80>
Enter a number: 4
Traceback (most recent call last):
File "./lists_of_functions2.py", line 37, in <module>
funcs[i]((3,5))
TypeError: list indices must be integers or slices, not function
What exactly do I need to add to get it to execute?
Upvotes: 0
Views: 29
Reputation: 1181
Its not very clear what you are trying to do. But if you are looking for a way to execute each function you just need to call them.
for func in funcs:
print(func())
you are getting error for funcs[i]((3,5))
because your i
is not declared in that scope. if you want to execute all the function for a given input i.e (3,5)
do
funcs=[f1,f2,f3,f4,f5,f6,f7,f8,f9,f10]
for func in funcs:
print(func(3,5))
if you are trying to execute a specific function withing the funcs
list, you have to provide a valid index
num=eval(input('Enter a number: '))
# if you want to execute num'th functions from the list
print(funcs[num](3,5))
Upvotes: 2
Reputation: 2399
i
is already a function. You are using for
loop to iterate over funcs
. instead of funcs[i]((3,5))
change it to i
directly i(3,5)
Upvotes: 0