【问题标题】:Defining functions in a Dictionary [duplicate]在字典中定义函数 [重复]
【发布时间】:2021-04-25 20:59:32
【问题描述】:

我正在尝试使用字典而不是 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 范围内),我都会将所有三个函数的结果作为输出。 为什么会发生这种情况?如何确保根据我的输入只调用一个函数?

【问题讨论】:

  • 定义字典时调用函数。 add(n1,n2) 调用然后打印值的函数。

标签: python dictionary


【解决方案1】:

试试{"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 作为参数调用它。

【讨论】:

  • 优秀。有用。非常感谢
【解决方案2】:
def add(a,b):
    return (f'Sum of {a} and {b} is:',(a+b))
def diff(a,b):
    return (f'Difference of {a} and {b} is:',(a-b)) 
def prod(a,b):
    return(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)}
print(dic[op])

您的程序正在打印所有值,因为您正在调用 dic 中的每个函数以及正在打印的每个函数。 而不是你应该返回然后使用键打印你需要的元素,在你的情况下是'op'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-12
    • 2019-08-21
    • 2019-03-23
    • 1970-01-01
    • 2020-05-06
    • 2014-06-26
    • 1970-01-01
    • 2019-02-18
    相关资源
    最近更新 更多