|
发表于 2020-5-23 10:57:16
|
显示全部楼层
- def get_digits(n):
- result = []
- if n < 10:
- result.append(n)
- return result
- else:
- result = get_digits(n//10)
- result.append(n%10)
- return result
- print(get_digits(243657))
复制代码
它运行得
- def get_digits(n):
- result = []
- if n < 10:
- result.append(n)
- return result
- else:
- get_digits(n//10)
- result.append(n%10)
- return result
- print(get_digits(243657))
复制代码
它运行得
为什么第一段代码在调用函数时,赋值result就不会清空列表呢?
是因为作用域的问题嘛?就是把result=[]屏蔽了。是不是可以这么理解:调用函数相当于外部函数与内部函数的关系,在内部函数中修改外部函数的局部变量,会把外部函数的局部变量屏蔽,即把result=[]屏蔽
请大佬指导一下 实在想不明白 |
|