gpt4 book ai didi

python - 当键值直接从字典分配给变量python时函数不起作用

转载 作者:行者123 更新时间:2023-12-05 03:35:54 24 4
gpt4 key购买 nike

所以我一直在学习 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}")

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

但是,当我进行以下更改时

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

我得到的输出是我想要的: desired output of calculator from above code snippet

我想知道为什么会这样。我不知道我的代码有什么问题。感谢和问候。

最佳答案

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

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

或者,

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

关于python - 当键值直接从字典分配给变量python时函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69761026/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com