[英]How do i end a while loop with blank input(str)
我正在嘗試制作一個可以將字符串添加到列表的程序。 例如“蘋果”。 它將它們按字母順序排序,並以空輸入結束循環
我已經嘗試過期望 valueErrors 和 SyntaxError 它們都不適用於字符串。 我也試過 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)
它將作為列表的輸入。 它會將 Apple、Banana 和 Orange 添加到列表中。 將它們按字母順序排列每個輸入。 它將以空輸入結束
列表列表:Apple Listalla 1 列表:蘋果列表列表:橙子列表 2 列表:蘋果、橙子列表列表:香蕉列表 3 列表:蘋果、香蕉、橙子列表列表:Listalla 3 列表:“空”蘋果、香蕉、橙色
您也可以在沒有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:")
您應該檢查傳遞的字符串是否為空並中斷循環:
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)
也許這會有所幫助:
ostos = []
while True:
string = str(input("Enter something: "))
if string != '':
print("You entered blank")
break
else:
ostos.append(string)
continue
這也有效:
if len(string) == 0: break
第一個只是檢查用戶輸入是否為空白,如果用戶按下回車鍵就會出現這種情況。 第二個檢查輸入字符串的長度是否為 0,只有當用戶按下回車時才會發生這種情況。
這對我來說可以。
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.