[英]Python scopes in For -Else
我正在學習python,無法理解下面的代碼片段中的flag發生了什么。 由於我已經在if套件中將標志更新為false,因此我希望從其他位置看到false的輸出,但是輸出顯示為true。 有人可以幫我了解這里發生了什么。
objects=[1,2,3,4,5]
found_obj = None
for obj in objects:
flag = True
if obj == 3:
found_obj = obj
print("found the required object ",found_obj)
flag= False
else:
print ('Status flag ::', flag)
以下是執行此代碼時得到的輸出
found the required object 3
Status flag :: True
但是,如果我脫離循環,則不會進入其他。
盡管這是事實,但沒有理由真正使用for..else
構造。 由於您正在搜索列表中的元素,因此盡早退出循環是有意義的。 因此,無論循環如何結束,您都應完全刪除else
並運行該print
。
此外,由於您嘗試設置是否已找到元素的標志,因此不應在每次迭代時都將其重置:
found_obj = None
flag = True
for obj in objects:
if obj == 3:
found_obj = obj
print("found the required object ",found_obj)
flag = False
break
print ('Status flag ::', flag)
最后,由於在找到元素時設置了found_obj
,因此實際上根本不需要該標志,因為值None
會告訴您您什么都沒找到,其他任何值都告訴您您確實找到了它:
found_obj = None
for obj in objects:
if obj == 3:
found_obj = obj
print("found the required object ",found_obj)
break
print ('Status flag ::', found_obj is None)
您在每次迭代的開始都設置flag = True
,因此在obj等於5的最后一次迭代中將其賦值為true
地方輸出true
您可能想通過從for循環中移出flag = True
來更正它:
flag = True
for obj in objects:
if obj == 3:
found_obj = obj
print("found the required object ",found_obj)
flag= False
break # no need to continue search
如果無法使用break
-ing,則為固定代碼:
objects=[1,2,3,4,5]
found_obj = None
flag = True # flag is set once, before the loop
for obj in objects:
# this sets the flag to True *on each iteration*, we only want it once!
# flag = True
if obj == 3:
found_obj = obj
print("found the required object ",found_obj)
flag= False
else:
print ('Status flag ::', flag)
這是一個循環的結構我知道由名證人的輕微變化,因為你只是在一個單一的“證人”興趣作證3
為對象的名單上。 一旦找到該見證人(元素3)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.