简体   繁体   中英

How do i end a while loop with blank input(str)

Im trying to make a program that you can add string to a list. For example 'Apple'. It sorts them into alphabetical order and ends the loop on a empty input

I've tried expect valueErrors and SyntaxError none of them work for string. I've also tried if(str(input) == Null) but that diden't work as id expect or want

try:
    ostos = []

    while True:
        ostos.append(str(input("Lisää listalle:")))
        print("Listalla on", len(ostos), "riviä:")
        ostos.sort()
        print(ostos)

except:
    print(ostos)

It would as for a input into the list. It would add Apple, Banana and Orange to the list. Put them in alphabetical order every input. And it would end on a empty input

Lisää listalle: Apple Listalla 1 riviä: Apple Lisää listalle: Orange Listalla 2 riviä: Apple, Orange Lisää listalle: Banana Listalla 3 riviä: Apple, Banana, Orange Lisää listalle: Listalla 3 riviä: 'Empty' Apple, Banana, Orange

You can also do this way without if .

ostos = []

s = input("Lisää listalle:")
while s:
    ostos.append(s)
    print("Listalla on", len(ostos), "riviä:")
    ostos.sort()
    print(ostos)

    s = input("Lisää listalle:")

You should check if passed string is empty and break loop:

ostos = []

while True:
    s = input("Lisää listalle:")
    if not s:  # check that s is not empty
        break   # break loop if is empty
    ostos.append(s)
    print("Listalla on", len(ostos), "riviä:")
    ostos.sort()
    print(ostos)

Maybe this will help:

ostos = []

while True:
    string = str(input("Enter something:  "))
    if string != '':
        print("You entered blank")
        break
    else:
        ostos.append(string)
        continue

This also works:

if len(string) == 0: break

The first one simply checks if the user input is blank, which will be the case if the user presses enter. The second one checks if the length of the entered string is 0,which only happens if user presses enter.

It works fine for me.

if __name__ == "__main__":

ostos = []

while True:
    input_data =  str( input("Input :" ))
    if input_data.rstrip() == "" :
        break

    ostos.append( input_data )

    ostos.sort()
    print(ostos)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM