[英]How can I get dictionary key as variable directly in Python (not by searching from value)?
[英]function not working when key value is assigned directly from dictionary to a variable python
所以我一直在學習 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設置為函數本身,在第二個塊中,將answer設置為將 func 應用於兩個輸入的結果。
你所看到的正是你應該看到的。 請注意,在第一個塊中,您獲取並保存該函數,然后在下一行使用兩個參數正確調用該函數,但不保存結果。
修復第一個塊的一種方法是更改:
answer = operations[operation_symbol]
answer(num1,num2)
到:
answer = operations[operation_symbol](num1,num2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.