Python local variable 我的知识盲点

谈笑风生 241 views 0 replies
admin #1 ·

简单写个 Hanoi Tower:
https://www.geeksforgeeks.org/problems/tower-of-hanoi-1587115621/1
Screenshot_20240903_185412

同样是在函数里面用外面的变量,为啥 Pycharm 给 num_movements 标红,ret 不标红呢?

问问 Github Copilot 得知:

Q: why is var num_movements unaccessible while ret is accessible in function my_toh?

A: The variable num_movements is inaccessible within the my_toh function because it is being modified inside the nested function, and Python treats it as a local variable within that scope. To modify a variable from an enclosing scope, you need to use the nonlocal keyword.

Q: but why is var ret not treated aslocal variable?
A: The variable ret is not treated as a local variable because it is not being modified within the nested function my_toh. In Python, variables that are only read within a nested function are considered to be from the enclosing scope unless explicitly declared as global or nonlocal. Since ret is only being appended to (which is a method call on the list object, not a reassignment), it is not considered a local variable within my_toh.