簡體   English   中英

如何在不首先添加到列表的情況下跳出循環?

[英]How do I break out of a loop without first appending to my list?

如何防止以下代碼將中斷命令“ N”附加到列表,從而打印“ N”?

xlist=[]
item=str(input("Item to add? (\"N\" to quit)"))
xlist.append(item)
while item != "N":
    item=str(input("Item to add? (\"N\" to quit)"))
    xlist.append(item)
    if item == "N":
        break

print(xlist)

您還可以通過以下方式簡化程序:

xlist=[]
item=input("Item to add? (\"N\" to quit)")
while item != "N":
    xlist.append(item)
    item=input("Item to add? (\"N\" to quit)")

編輯:按照注釋中的建議刪除了多余的str()調用。

在while循環中, item != "N":永遠不會為假,因為您可以手動退出循環。

一個有可能在某個輸入上結束的while lop的更好方法是避免使用兩個輸入語句,這將使用無限while循環( while True ),然后在滿足所需條件時中斷:

xlist=[]
while True:
    item=str(input("Item to add? (\"N\" to quit)"))
    if item.upper() == "N":
        break
    xlist.append(item)

print(xlist)

另外,我添加了upper() ,使其可以接受nN

這里有一些提示:

  • 您可以使用'this "kind" of string'來避免\\
  • 您實際上可以通過重新引入if語句來避免使用同一行代碼
    • 如果您正在使用Python2(不應該是初學者),則應該使用raw_input ,而不是str(input(...)) 如果您使用的是Python3,則無需強制轉換為str,它已經是str。
    • 您可以使用.lower() (或.upper() )方法讓用戶使用nN

看起來像這樣:

xlist = []
item = ''
while True:
    item = input('Item to add? ("N" to quit): ')
    if item.lower() == 'n':
        break
    else:
        xlist.append(item)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM