首页 > 解决方案 > 第一个输入未插入列表

问题描述

我正在编写一个程序来接受用户输入以逐字构建句子。用户完成后,它应该显示列表中的句子和单词数量。我知道我的代码不完整,我只针对一个问题请求帮助。截至目前,我无法将第一个输入追加或插入到列表中,而其他输入则是。任何帮助都会很棒。我一直在寻找一段时间没有进展。

代码:

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()

标签: python

解决方案


您的代码存在很多问题,但是您的单词未附加到列表中的主要原因是可变的默认参数通常不会执行您想要的操作。

相反,只需在一个函数中执行所有操作。

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()

推荐阅读