What gets printed?()
counter = 1 def doLotsOfStuff(): global counter for i in (1, 2, 3): counter += 1 doLotsOfStuff() print counter
题目排版粗糙有误,按惯例先整理一下:
counter = 1
def doLotsOfStuff():
global counter
for i in (1, 2, 3):
counter += 1
doLotsOfStuff()
print counter
此题不难,主要是考察 global 的意义,即在局部作用域 doLotsOfStuff() 函数中,声明对全局作用域中的 counter 变量的引用,详情可参考:
最后要注意第 5 行的坑,是 counter += 1
而不是 counter += i
,因此答案是 4 而不是 7,选答案 C。