这段代码有很多问题,如果我没有正确解释它们,我深表歉意,我对 python 世界还是比较陌生。
没有中央集线器来存储当前插入函数中的列表“单词”和“描述”。当您调用该函数时,您实际上并没有为它们分配任何变量。每次调用该函数时,您都会用一个空列表覆盖您添加到这些列表中的任何内容。此外,通过在查找函数中调用函数 insert,您不会调用所需的值。您正在运行整个功能,这不是您想要发生的。
我将首先更改您的词汇表功能以充当程序的中心枢纽。请注意,“单词”和“描述”列表位于 while 循环之外,因此它们可以保留信息。我还更改了 "if answer == "3"" 以打破循环而不是返回任何内容。最后,在调用 insert 和 lookup 时,我给它们变量以在函数中使用。
def glossary():
words = []
descriptions = []
while True:
print("\nMenu for glossary\n Type 1 to insert a new word.\n Type 2 to lookup a word.\n Type 3 to exit.\n")
answer = input("Write your answer here: ")
if answer == "1":
insert(words, descriptions)
elif answer == "2":
lookup(words, descriptions)
elif answer == "3":
break
else:
print("\nTry again!\n")
函数 insert 看起来也有点不同,如前所述,列表“单词”和“描述”已从函数中删除。此外,当调用该函数时,它会被赋予要使用的变量。这个函数没有返回语句,据我所知这很好。如果您真的想要一个,可以将其更改为拥有一个。
def insert(words, descriptions):
word = input("Type the word you want to add: ")
words.append(word)
description = input("Descripe the word you want to add: ")
descriptions.append(description)
最后是查找功能。它看起来非常不同。它不再调用其中的另一个函数,它主要充当打印列表的函数。
def lookup(words, descriptions):
print('\n')
print(*words, sep = ", ")
print(*descriptions, sep = ", ")
当然,我们调用函数词汇表来运行程序。
glossary()
整个代码:
def glossary():
words = []
descriptions = []
while True:
print("\nMenu for glossary\n Type 1 to insert a new word.\n Type 2 to lookup a word.\n Type 3 to exit.\n")
answer = input("Write your answer here: ")
if answer == "1":
insert(words, descriptions)
elif answer == "2":
lookup(words, descriptions)
elif answer == "3":
break
else:
print("\nTry again!\n")
def insert(words, descriptions):
word = input("Type the word you want to add: ")
words.append(word)
description = input("Descripe the word you want to add: ")
descriptions.append(description)
def lookup(words, descriptions):
print('\n')
print(*words, sep = ", ")
print(*descriptions, sep = ", ")
glossary()
这是一个非常奇怪的问题,如果我没有正确理解您的问题,我深表歉意。为了我的理智,我还更改了一些打印输出。我不知道你想用这段代码做什么,但我认为获取“单词”和“描述”的特定部分的值以进行编辑或打印的一种有趣方法可能是通过索引访问它们。