CodySDEV
CodySDEV

Reputation: 83

First input not inserting into List

I am writing a program to accept user input to build a sentence word-by-word. After the user is done it is supposed to display the the sentence and the amount of words in the list. I know my code isn't complete and I am only requesting help for one issue. As of the moment I cannot get the first input to append or insert into the list, while others are. Any help would be great. I have been searching for awhile with no progress.

Code:

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

Upvotes: 2

Views: 273

Answers (1)

tyleax
tyleax

Reputation: 1780

There's lots of issues with your code, but the main reason why your word is not being appended to your list is because mutable default arguments don't generally do what you want.

Instead just perform everything in a single function.

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

The detailed answer is The first time you call inputFunc() inside main() you pass an empty list:

def main():
    wordList = []
    inputFunc(wordList=[])

When you call it again via recursion inside inputCalc(choice) you call inputFunc() without passing any arguments thus using a different list, the pre-initialized list.

def inputCalc(choice):
    while choice == 'y':
        inputFunc()

Upvotes: 2

Related Questions