繁体   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