[英]What happens when loop gets to the end?
我是python初學者,沒有以前的編程知識。 我為這個話題的名字道歉,但我根本無法做出更好的話題。 這就是我想要的:
letter = "w" # search for this letter in the list bellow
listL = ["z","b","y","a","c"]
for let in listL:
if let == letter:
print "found it"
break
else:
if let == listL[-1]:
print "nope can't find it"
continue
我有一個字母列表,我想在該列表中搜索特定的字母。 如果我找到了這封信,那么一切都很好,for循環應該停止。 如果我沒有找到它,我希望循環停止當前迭代,並嘗試使用列表中的下一個字母。 如果列表中的單個字母沒有該特定字母,那么它應該打印“nope找不到它”。
上面的代碼工作。 但我想知道這是否可以寫得有點清楚? 顯然,我並不是指“先進”,而是學者的方式,一種來自書本的方式。
謝謝。
Python為for循環提供了一個else
語句,如果循環結束而不被破壞則執行該語句:
for let in llistL:
if let == letter:
print("Found it!")
break
else:
print("nope could'nt find it")
那將是for
循環的“學者方式”,但是如果你只測試列表中元素的存在,Arkady的答案就是要遵循的答案。
怎么樣:
if letter in listL:
print "found it"
else:
print "nope..."
只需在使用
if let in listL:
print("Found it")
else:
print("Not found")
編輯:你快30秒了,恭喜;)
在Python中實際上有一個for: else:
構造,如果for
循環沒有 break
則else
運行:
for let in listL:
if let == letter:
print("Found it")
break
else:
print("Not found")
或者,您可以使用list.index
,它將在列表中找到項目的索引,如果找不到則引發ValueError
:
try:
index = listL.index(letter)
except ValueError:
print("Not found")
else:
print("Found it")
你的循環將繼續循環,直到它破壞(找到它!)或列表用盡。 你不需要做任何特別的事情來“停止當前的迭代,並嘗試使用列表中的下一個字母”。 當字母不匹配時我們不需要continue
,只要有更多的字母要檢查,這將自動發生。
在我們搜索整個列表后,我們只想顯示“nope找不到它”,所以我們不需要檢查直到結束。 這個else
語句對應於for
循環,而不是前一代碼中的if
。
letter = "w" # search for this letter in the list bellow
listL = ["z","b","y","a","c"]
for let in listL:
if let == letter:
print "found it"
break #found letter stop search
else: #loop is done, didn't find matching letter in all of list
print "nope can't find it"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.