意外的TypeError:'str'对象不可调用

时间:2014-06-29 20:15:02

标签: python

我的程序出错了,你能帮帮忙吗?

这是相关代码:

    def play():
        play = input("Do you want to play again? (y/n) :")
        if play == "y":
            game(0)
        if play == "n":
            quit()
        if play == "Debug":
            game(1)
        if play != "y" or "n" or "Debug":
            play()

这是错误:

    Well Done You Win!!!!!
    You took this many tries : 
    1
    Game Was Made By Ross Searle!!!
    Do you want to play again? (y/n) :gnl;rgn;
    Traceback (most recent call last):
      File "C:\Users\ross\Desktop\game.py", line 67, in <module>
        firstplay()
      File "C:\Users\ross\Desktop\game.py", line 7, in firstplay
        game(0)
      File "C:\Users\ross\Desktop\game.py", line 55, in game
        play()
      File "C:\Users\ross\Desktop\game.py", line 23, in play
        play()
    TypeError: 'str' object is not callable
    >>>    

我试图这样做,只要你输入任何东西就重复这个问题。

2 个答案:

答案 0 :(得分:3)

这里的问题是你有一个名为play的函数,并且在该函数中你为字符串play指定了相同的名称。现在play()将尝试调用一个字符串对象,这显然会失败。错误消息实际上告诉你:

TypeError: 'str' object is not callable

解决方案是为用户输入另一个名称,例如:

play_input = input("Do you want to play a Game? (y/n) :")

我也在提示中修正了错误;)

答案 1 :(得分:3)

play = input("Do ypu want to play a Game? (y/n) :")

这将play定义为字符串变量。

您还play作为函数:

def play():

当Python真正处理一个名为play的字符串时,当你试图调用函数play时,Python不知道该怎么做。 Python只是认为你试图将字符串用作函数,因为这是不可能的,然后它会给你错误消息TypeError: 'str' object is not callable

要修复此更改您的名称,以便不使用变量名称作为函数名称,反之亦然。