Python:在自身内部调用函数时出错

时间:2013-10-12 15:26:00

标签: python function dictionary

我使用python创建了一个简单的字典程序。

dictionary = {"testword" : "testmeaning"}
y = ["y", "Yes", "Y", "YES", "yes", "yep", "YEP", "Yep"]
n = ["n", "No", "N", "no", "NO", "nope", "Nope", "NOPE"]

def ans():
    ans = raw_input("Y/N")
    if ans in y:
        meaning = raw_input("Type the meaning.")
        dictionary[x] = meaning
        print "Added!. Thanks for using the dictionary."
        reload
    elif ans in n:
        print "Thanks for using the dictionary."
    else:
        print "Type either Y or N."
        ans()

def add_word():
    print "Do you want to add it?"
    ans()
def close_ans():
    close_ans = raw_input("Y/N")
    if close_ans in y:
        quit
    elif close_ans in n:
        in_dict()
    else:
        print "Type either Y or N"
        close_ans()

def close():
    print "Close?"
    close_ans()

def in_dict():
    global x
    x = raw_input("Type the word.")
    if x in dictionary:
        print dictionary[x]
        close()
    else:
        print "This word isn't in the dictionary yet."
        add_word()
        close()

in_dict()

代码非常自我解释。我用一个名为“testword”的单词创建了一个字典,其值为“testmeaning”。还有一个正面和负面答案的列表,用于确定用户是否在某些情况下同意或拒绝。它首先调用函数in_dict,它要求用户输入单词。如果单词在字典中,则打印含义并要求关闭。如果不是,则询问用户是否要添加它。如果您不理解它,请再次查看代码。如果用户键入除列表y或n中的单词之外的其他内容,则再次询问。但是,它不起作用。如果我输入除y和n中的单词以外的任何内容,它会显示以下错误。

Traceback (most recent call last):
    File "C:\Users\Prateek\Desktop\dictionary.py", line 46, in <module>
      in_dict()
    File "C:\Users\Prateek\Desktop\dictionary.py", line 43, in in_dict
      add_word()
    File "C:\Users\Prateek\Desktop\dictionary.py", line 20, in add_word
      ans()
    File "C:\Users\Prateek\Desktop\dictionary.py", line 16, in ans
      ans()
TypeError: 'str' object is not callable

2 个答案:

答案 0 :(得分:1)

通过执行以下句子,您可以创建局部变量ans。阴影全局函数ans

ans = raw_input("Y/N")

使用不同的名称。

答案 1 :(得分:0)

那是因为,在函数ans内,你使ans等于这一行的字符串:

ans = raw_input("Y/N")

这样做掩盖了函数ans

要解决您的问题,请选择其他变量名称或重命名您的功能。