Search code examples
pythonlistwhile-loop

While loop only runs the elif statement once and doesn't flow back through the rest of the loop


I am trying to write a program that appends each line of user input to a list. Once the user enters '', the loop should break. When their is more than 1 line of input the code executes the way it is intended.

However, there is an elif statement for when a users first input is '', that asks the user to enter something besides ''.

Upon testing this part out, the program prints the 'Enter a list' line you can see below, but then it ignores the rest of the program. If you enter '' again, the program exits and outputs [] when it should be going through the loop until there is a user input that is not ''.

Also if you do enter a few lines into the list, the program does not remove the '' situated at list1[-1].

The desired end output should have no '' in the list.

list1 = list()
def listt():
    counter = 0
    print("Please enter your shopping list:")
    while counter < 1:
        ask = input()
        list1.append(ask)
        if len(list1) > 1 and list1[-1] == '':
            list1.remove(list1[-1])
            counter += 1
            break
        elif len(list1) == 1 and list1[0] == '':
            print('Enter a shopping list:')
    print(list1)

listt()

Solution

  • The simple fix is to refactor to only add to the list when what you get isn't an empty string.

    def listt():
        list1 = list()
        print("Please enter your shopping list:")
        while True:
            ask = input()
            if not ask:
                if not list1:
                    print("Try again")
                    continue
                else:
                    break
            list1.append(ask)
        return list1
    
    print(listt())
    

    Notice also how I refactored to make list1 a local variable which the function returns.