我正在写一个程序,接受用户输入,逐字造句。用户完成后,应该显示句子的名称和列表中的字数。我知道我的代码不完整,我只请求一个问题的帮助。到目前为止,我无法获得要追加或插入到列表中的第一个输入,而其他输入是。任何帮助都会很好。我已经找了一段时间没有进展了。你知道吗
代码:
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()
你的代码有很多问题,但是你的单词没有被添加到你的列表中的主要原因是因为可变的默认参数通常不是你想要的。你知道吗
相反,只需在一个函数中执行所有操作。你知道吗
详细答案是,当您第一次在
main()
内调用inputFunc()
时,您会传递一个空列表:当您通过
inputCalc(choice)
内的递归再次调用它时,您调用inputFunc()
,而不传递任何参数,因此使用不同的列表,即预初始化列表。你知道吗相关问题 更多 >
编程相关推荐