[英]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.