我还应该指出,我使用的是python 3.6
funcs = [add,sub,mult,div,power]
上面是函数索引
chosenfunc = chooseFunc()
for i in funcs:
if i == chosenfunc:
i(x,y)
以上就是我试图访问它的方式。
所以它基本上运行add()
。
如果相关,我的add函数写为:
def add(x,y):
print(f"Result of {x} + {y}: {(float(x)) + (float(y))}")
如何让它运行我的函数?它目前什么都不做
import fractions
funcs = [add,sub,mult,div,power]
def chooseFunc():
return input("Choose a function from between Add, Subtract, Multiply, Divide, power: ")
def numtofloat(num):
return float(num)
def add(x,y):
print(f"Result of {x} + {y}: {(numtofloat(x)) + (numtofloat(y))}")
def sub(x,y):
print(f"Result of {x} - {y}: {(numtofloat(x)) - (numtofloat(y))}")
def mult(x,y):
print(f"Result of {x} * {y}: {(numtofloat(x)) * (numtofloat(y))}")
def div(x,y):
print(f"Result of {x} / {y}: {(numtofloat(x)) / (numtofloat(y))}")
def power(x,y):
print(f"Result of {x} ^ {y}: {(numtofloat(x)) ^ (numtofloat(y))}")
chosenfunc = chooseFunc()
for i in funcs:
if i == chosenfunc:
i()
编辑以添加完整代码
下面是你如何做到这一点的
编辑:问题已更改:)
添加了x,y以使用dict传递给函数以保持函数映射,并在映射之前移动了函数def
相关问题 更多 >
编程相关推荐