簡體   English   中英

Python TypeError -: 'str' object 不可調用

[英]Python TypeError - : 'str' object is not callable

這是我的代碼。

n1, n2 = (int(input("Enter number: ")) for _ in range(2))
print("Select Your Choice: ")
print(" 1: Addition",
       "2: Substraction",
       "3: Multiplication",
       "4: Division")
choice = int(input())

switcher = {
        1: "Addition",
        2: "Substraction",
        3: "Multiplication",
        4: "Division",
    }
def addition(n1,n2):
    n1 += n2
    return n1

def substraction(n1,n2):
    n1 -= n2
    return n1

def multiplication(n1,n2):
    n1 *= n2
    return n1

def division(n1,n2):
    n1 /= n2
    return n1

def calculator(choice,n1,n2):
    return switcher.get(choice,"Invalid")(n1,n2)

print(calculator(choice,n1,n2))

我得到以下錯誤。

> Traceback (most recent call last):   
> simple calculator with dictionary.py", line 36, in <module>
> print(calculator(choice,n1,n2))   
> simple calculator with dictionary.py", line 34, in calculator

> > return switcher.get(choice,"Invalid")(n1,n2) 
> TypeError: 'str' object is not callable

誰能解決這個錯誤?

switcher中的值必須是您定義的函數,而不是字符串。

switcher = {
    1: addition,
    2: substraction,
    3: multiplication,
    4: division,
}

switcher的初始化放在函數定義之后。

對於無效輸入,您仍然會收到“字符串不可調用”錯誤,因為

"Invalid"(n1, n2)

不是有效的 function 調用。 調整calculator以針對無效輸入執行其他操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM