該程式正在執行所有功能,我只希望它執行在 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])
uj5u.com熱心網友回復:
func = function_call[operation]
print(func(num1, num2))
Python 中的函式是物件。因此,您可以將它們作為物件處理并在其他物件之間進行互操作。您只需要提供運行它的引數 ( call)
uj5u.com熱心網友回復:
問題是,當您定義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))
uj5u.com熱心網友回復:
function_call = {
" " : add(num1, num2),
"-" : subtract(num1, num2),
"*" : multiply(num1, num2),
"/" : divide(num1, num2),
}
因為函式名后面有括號,所以在定義字典時會呼叫它們。
如果你不想這樣,那么不要放括號:
function_call = {
" " : add,
"-" : subtract,
"*" : multiply,
"/" : divide,
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/473190.html
上一篇:跨CPU內核并行化代碼,該代碼迭代總700K條目的嵌套字典
下一篇:如何構建詞典詞典?
