【发布时间】: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