我写了如下代码,老师帮我看下问题
来源:7-3 for 与 range

PIPIX
2019-07-01
def testpush(i, result=[]):
if i == 5:
return result
i += 1
result.append(i)
return testpush(i, result)
result = testpush(0)
result = testpush(0)
result = testpush(0)
print(result)
结果是这样
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
def testpush(i, result=[]):
if i == 5:
return result
i += 1
result.append(i)
return testpush(i, result)
result = testpush(0, [])
result = testpush(0, [])
result = testpush(0, [])
print(result)
结果是这样
[1, 2, 3, 4, 5]
请问函数默认变量的作用域是怎样的?为什么会出现上面两种不同的情况?
写回答
1回答
-
7七月
2019-07-02
第一个函数,你一直在复用一个列表,但第二个你每次都初始化了一个新列表。这样的问题没啥意义,也很难看清楚,真想看清楚,打断点跟踪流程一步步的走。
022019-07-04
相似问题