Lets there is a function which has a defined variable x and this function has another function defines inside it which has another function defines inside. And in the innermost function we want to access x. Do we still use nonlocal x in that case to access x?
Doubt regarding accessing of variable
Hey @Nitin-Bhattacharyya-2319140631658033, let me clear this thing using 4 cases with screenshots of code as well.
- In the very first case we just tried to print the value of x, so there will not be any error with this and code will access the x defined in the most outer function.
- Case 2 when we first tried changing the value of the x, so this time an error pops up as expected with the same error message.
- We updated the value but after using non local. No error pops up as expected and we can update value of x defined in f1.
- This is an addon you haven’t asked it, but its better to be cleared about this as well, if we define x in f1 and f2 as well. Then when we specify non local in f3, it will use the value defined in the bottom up fashion. So it will try searching first in f2 then in f1. here it gets value in f2, so it will use that and change that only.
Hope this resolved your doubt.
thanks the rest cases are clear now,but in the last case what if we dont want x=8 to be accessed and only x=5 to be accesed?
Hey @Nitin-Bhattacharyya-2319140631658033, no there is no way you can do that.
Hope this resolved your doubt. Plz mark the doubt as resolved as well in my doubts section.