简体   繁体   English

如何用空白输入(str)结束while循环

[英]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.我已经尝试过期望 valueErrors 和 SyntaxError 它们都不适用于字符串。 I've also tried if(str(input) == Null) but that diden't work as id expect or want我也试过 if(str(input) == Null) 但这并没有像 id 期望或想要的那样工作

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.它会将 Apple、Banana 和 Orange 添加到列表中。 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列表列表:Apple Listalla 1 列表:苹果列表列表:橙子列表 2 列表:苹果、橙子列表列表:香蕉列表 3 列表:苹果、香蕉、橙子列表列表:Listalla 3 列表:“空”苹果、香蕉、橙色

You can also do this way without if .您也可以在没有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.第二个检查输入字符串的长度是否为 0,只有当用户按下回车时才会发生这种情况。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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