[英]How do I break out of my while loop without using the most popular functions?(sys.exit,break,etc.)
[英]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()
,使其可以接受n
或N
這里有一些提示:
'this "kind" of string'
來避免\\
raw_input
,而不是str(input(...))
。 如果您使用的是Python3,則無需強制轉換為str,它已經是str。 .lower()
(或.upper()
)方法讓用戶使用n
或N
看起來像這樣:
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.