我正在编写一个程序来接受用户输入,以逐个单词地构建句子。用户完成后,应该在列表中显示句子和单词数量。我知道我的代码还不完整,我只需要为一个问题寻求帮助。到目前为止,我无法获得第一个输入来追加或插入到列表中,而其他输入则是。任何帮助都会很棒。我已经搜索了一段时间,没有任何进展。
代码:
index = 0
def main():
wordList = []
inputFunc(wordList = [])
def inputFunc(wordList = []):
global index
print("To make a sentence, enter one word at a time... ")
wordInput = input("Enter word... : ")
wordList.insert(index,wordInput)
index += 1
choice = input("(y = Yes, n = No, r = Reset List)Another word?: " )
inputCalc(choice)
completeList(wordList)
def inputCalc(choice):
while choice == 'y':
inputFunc()
while choice == 'n':
return
while choice == 'r':
clearList()
def completeList(wordList):
print(wordList)
exit()
def clearList():
wordList.clear()
main()
main()
答案 0 :(得分:2)
您的代码有很多问题,但是未将单词附加到列表中的主要原因是可变的默认参数通常不能满足您的要求。
相反,只需执行一个功能即可。
def main():
inputFunc()
def inputFunc():
running = True
wordList = []
while running:
print("To make a sentence, enter one word at a time... ")
wordInput = input("Enter word... : ")
wordList.append(wordInput)
while True:
choice = input("(y = Yes, n = No, r = Reset List)Another word?: " )
if choice == 'y':
break
elif choice == 'n':
running = False
break
elif choice == 'r':
wordList = []
break
print(wordList)
if __name__ == "__main__":
main()
详细的答案是:第一次在inputFunc()
内部调用main()
时,您会传递一个空列表:
def main():
wordList = []
inputFunc(wordList=[])
当您在inputCalc(choice)
内部通过递归再次调用它时,您将在不传递任何参数的情况下调用inputFunc()
,从而使用另一个列表(即预先初始化的列表)。
def inputCalc(choice):
while choice == 'y':
inputFunc()