程序正在执行所有函数,我只希望它执行function_call[operation]字典键中调用的函数。
# Define functions for addition, subtraction, division, and multiplication
# Write the equation and its output to a file
def add(num1, num2):
answer = num1 + num2
with open("equation.txt", "w") as equation:
return equation.write(f" {num1} + {num2} = {answer}")
def subtract(num1, num2):
answer = num1 - num2
with open("equation.txt", "w") as equation:
return equation.write(f" {num1} - {num2} = {answer}")
def multiply(num1, num2):
answer = num1 * num2
with open("equation.txt", "w") as equation:
return equation.write(f" {num1} * {num2} = {answer}")
def divide(num1, num2):
answer = num1/num2
with open("equation.txt", "w") as equation:
return equation.write(f" {num1} / {num2} = {answer}")
# input first number
# input operation
# input second number
num1 = int(input("Please enter a valid first number: "))
operation = input(''' Choose between:
+ : addition operation
- : subtract operation
* : multiply operation
/ : divide operation
: ''')
num2 = int(input("Please enter a valid second number: "))
# create dictionary with operation input as key and corresponding value as function
# call diction value with operation variable as key to call the desired function or operation to be executed
function_call = {
"+" : add(num1, num2),
"-" : subtract(num1, num2),
"*" : multiply(num1, num2),
"/" : divide(num1, num2),
}
print(function_call[operation])
func = function_call[operation]
print(func(num1, num2))
Python中的函数是对象。所以你可以把它们当作对象来处理,并在其他对象之间进行互操作。您所需要的只是提供运行它的参数(call
)
问题是,当您定义function_call
字典时,您调用了所有的函数并将这些调用的结果存储在字典中:
function_call = {
"+" : add(num1, num2),
"-" : subtract(num1, num2),
"*" : multiply(num1, num2),
"/" : divide(num1, num2),
}
相反,将函数本身放在字典中,而不调用它们:
function_call = {
"+" : add,
"-" : subtract,
"*" : multiply,
"/" : divide,
}
,然后在从字典中获取后调用相应的函数:
print(function_call[operation](num1, num2))
function_call = {
"+" : add(num1, num2),
"-" : subtract(num1, num2),
"*" : multiply(num1, num2),
"/" : divide(num1, num2),
}
由于函数名后面有圆括号,因此在定义字典时它们被称为。
如果你不想这样,那就不要加上括号:
function_call = {
"+" : add,
"-" : subtract,
"*" : multiply,
"/" : divide,
}