我用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