我正在尝试用python制作一个基本的计算器。我包括一个函数索引

2024-09-29 01:30:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我还应该指出,我使用的是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()

编辑以添加完整代码


Tags: of函数divaddfordefresultfloat
1条回答
网友
1楼 · 发布于 2024-09-29 01:30:19

下面是你如何做到这一点的

def add(x, y):
    print(x + y)


funcs = [add, ]


def chooseFunc():
    # take input here for function by index or something
    return 0


chosenfunc = chooseFunc()

for i in range(len(funcs)):
    if i == chosenfunc:
        funcs[i](2, 3)

编辑:问题已更改:)

import fractions


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))}")


funcs = {"add": add, "sub": sub, "mult": mult, "div": div, "power": power}


def chooseFunc():
    return input("Choose a function from between add, sub, mult, div, power: ")


x, y = 2, 3

chosenfunc = chooseFunc()
for i in funcs.keys():
    if i == chosenfunc:
        funcs[i](x, y)

添加了x,y以使用dict传递给函数以保持函数映射,并在映射之前移动了函数def

相关问题 更多 >