当键值直接从字典分配给变量时函数不工作



我学习python大概有10天了,我发现python有一些奇怪的行为。

下面的代码片段和输出图像:

#calculator
def add(n1,n2):
"""Adds two numbers"""
return n1 + n2
def subtract(n1,n2):
"""Subtracts two numbers"""
return n1 - n2
def multiply(n1,n2):
"""Multiplies two numbers"""
return n1 * n2
def divide(n1,n2):
"""Divides two numbers"""
return n1 / n2
#we do not add paranthesis because we want to store the names of functions in the dictionary
#we do not want to assign the function and trigger a call for execution itself. Hence only the name of the function will suffice.
operations = {
'+' : add,
'-': subtract,
'*': multiply,
'/': divide,
}
num1 = int(input("What is this first number you want to enter ?n"))
num2 = int(input("What is this second number you want to enter ?n"))
for operation_symbols in operations:
print(operation_symbols)
operation_symbol = input("Pick a symbol from the list above for your calculations")
answer = operations[operation_symbol]
answer(num1,num2)
print(f"{num1} {operation_symbol} {num2} = {answer}")

当我写这段代码时:我的输出如下图:输出

但是,当我做以下修改

#calculator
def add(n1,n2):
"""Adds two numbers"""
return n1 + n2
def subtract(n1,n2):
"""Subtracts two numbers"""
return n1 - n2
def multiply(n1,n2):
"""Multiplies two numbers"""
return n1 * n2
def divide(n1,n2):
"""Divides two numbers"""
return n1 / n2
#we do not add paranthesis because we want to store the names of functions in the dictionary
#we do not want to assign the function and trigger a call for execution itself. Hence only the name of the function will suffice.
operations = {
'+' : add,
'-': subtract,
'*': multiply,
'/': divide,
}
num1 = int(input("What is this first number you want to enter ?n"))
num2 = int(input("What is this second number you want to enter ?n"))
for operation_symbols in operations:
print(operation_symbols)
operation_symbol = input("Pick a symbol from the list above for your calculations")
operation_function = operations[operation_symbol]
answer = operation_function(num1,num2)
print(f"{num1} {operation_symbol} {num2} = {answer}")

我得到的输出是我想要的:上述代码片段

中计算器的期望输出我想知道为什么会发生这种情况。我不知道我的代码是怎么回事。谢谢你的问候。

在第一个代码片段中,您试图打印对函数本身的引用,而不是函数调用answer(num1,num2)的结果。修改如下,您将得到想要的结果:

print(f"{num1} {operation_symbol} {num2} = {answer(num1, num2)}")

或者

result = answer(num1, num2)
print(f"{num1} {operation_symbol} {num2} = {result}")

在第一个非工作代码块中,您设置:

answer = operations[operation_symbol]

在第二个块中,你设置:

answer = operation_function(num1,num2)
因此,在第一个数据块中,您将答案设置为函数本身,而在第二个数据块中,您将答案设置为将函数应用于两个输入的结果。

你所看到的正是你应该看到的。请注意,在第一个块中,捕获并保存函数,然后在下一行使用两个参数正确调用函数,但不保存结果。

修复第一个块的一种方法是修改:

answer = operations[operation_symbol]
answer(num1,num2)

:

answer = operations[operation_symbol](num1,num2)

最新更新