Search code examples
pythonwhile-loopconditional-statements

While loop, how do I condition for when input equals nothing?


Create a program that will keep track of items for a shopping list. The program should keep asking for new items until nothing is entered (no input followed by enter key). The program should then display the full shopping list

How do I write the condition so it works?

The code I'm writing looks like this:

x = []

i = 0
while i != '':
    x.append(input('what u want?'))
    i = i + 1

print(x)
```
`


Solution

  • Find len of user input & check with if accordingly

    x = []
     
    while 1:
        ask= input('what u want?')
        if len(ask)>0:
            x.append(ask)
    
        else:
            print("Good bye")
            break
       
    print(x)
    

    output #

    what u want?rice
    what u want?sugar
    what u want?
    Good bye
    ['rice', 'sugar']
    

    Code correction

    It is not ideal to choose hit enter to exit the loop. You need to assign keyword to make sure user really wants to exit.

    x = []
    
    while 1:
        ask= input('what u want?')
        if len(ask)>0 and ask !="finish":
            x.append(ask)
        else:
            print("Good bye")
            break
      
    print(x)
    

    With this user will have clarity when to checkout.

    More interactive way:

    x = []
    
    
    while 1:
        ask= input('what u want?')
        if len(ask)>0 and ask !="finish":
            x.append(ask)
    
        else:
            confirmation = input('Do you really want to exit? - yes or no')
            if confirmation =="yes":
                
                print("Good bye")
                break
            else:
                print("Let's continue shopping")
                pass       
    
    print(x)