在字典中定义函数

朱奈德·艾哈迈德 |

我正在尝试使用字典而不是 if-else 条件来实现计算器操作。然而,不是只运行一个必需的函数,而是运行字典中定义的所有函数。以下是代码:\n

def add(a,b):
    print(f'Sum of {a} and {b} is:',(a+b))
def diff(a,b):
    print(f'Difference of {a} and {b} is:',(a-b))
def prod(a,b):
    print(f'Product of {a} and {b} is:',(a*b))
n1 = 5
n2 = 3
op = int(input("Enter the command for operation (1-3): "))
dic = {1: add(n1,n2), 2: diff(n1,n2), 3: prod(n1,n2)}
dic[op]

如果我输入 3,则预期输出为 15,因为只有值 prod(n1,n2) 应该为键 3 触发。但是,无论我的输入是什么,我都将所有三个函数的结果作为输出(在1-3 的范围)。为什么会发生这种情况,我如何确保根据我的输入只调用一个函数?

下载比萨

试试{"a" : print("a"), "b" : print("b")}如您所见,即使您不调用它,它仍然会打印 a 和 b。这是由于正在评估的项目。

不是将函数的结果放入 dict (结果都是 None,因为您没有从函数中返回任何内容),您可以将函数本身放入:

def add(a,b):
    print(f'Sum of {a} and {b} is:',(a+b))
def diff(a,b):
    print(f'Difference of {a} and {b} is:',(a-b))
def prod(a,b):
    print(f'Product of {a} and {b} is:',(a*b))
n1 = 5
n2 = 3
op = int(input("Enter the command for operation (1-3): "))
dic = {1: add, 2: diff, 3: prod}
dic[op](n1, n2)

此代码采用指定索引处的函数,并使用 n1 和 n2 作为参数调用它。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章