所以我一直在學習 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}")
我得到的輸出是想要的: 上面代碼片段的計算器的期望輸出
我想知道為什么會發生這種情況。我不知道我的代碼是怎么回事。感謝致敬。
uj5u.com熱心網友回復:
在第一個代碼片段中,您嘗試列印對函式本身的參考,而不是函式呼叫的結果answer(num1,num2). 按如下方式更改它,您將獲得所需的結果:
print(f"{num1} {operation_symbol} {num2} = {answer(num1, num2)}")
或者,
result = answer(num1, num2)
print(f"{num1} {operation_symbol} {num2} = {result}")
uj5u.com熱心網友回復:
在第一塊非作業代碼中,您設定:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/341437.html
下一篇:如何在特定的懸停卡片上顯示訊息?
