1. for x in [Iterable] 中的x 作用域
2. 作用域,待补充
————————————————————————————————————
1. for x in [Iterable] 中的x 作用域
今天科大讯飞笔试题:
第二题怎么debug都有点问题。
然后发现是for循环的target list 只要不为空,里面的x被赋值,和函数bonus的形参x冲突。
因为for循环没有作用域(scope)。
def bonus(m,x,k,p):
# print m,x,k,p
error = 0
right = 0
for x in p:
if x == 1:
right += 1
else:
error += 1
def bonus(m,x,k,p):
# print m,x,k,p
error = 0
right = 0
for _i in p:
if _i == 1:
right += 1
else:
error += 1
参考:https://docs.python.org/2.7/reference/compound_stmts.html#the-for-statement
loop循环后target list不删除;但是如果sequence是空则整个循环不会赋值。
The target list is not deleted when the loop is finished, but if the sequence is empty, it will not have been assigned to at all by the loop.
网友评论