Oh, boy, there's some code on the screen and it looks terribly confusing.
This is an example of a really convoluted, complicated function that you would never write, but it'll
be good for exercise purposes.
And we're talking specifically about this right here called nonlocal.
It's actually a new keyword in Python three.
And as you can see, my Reppel doesn't even notice it.
So it doesn't even highlighted in blue because it is a new feature.
But I do want to talk to you about it and let you know what it does.
The nonlocal key keyword is used to refer to this part, this parent local.
It's a way for us to say, hey, I want to use a variable that is not a global variable, but is outside
of the scope of my function.
So based on that definition, try and pause the video and see what this function might do, I'll run
it right now and then go through the code if I click run.
This is what we get.
So let's talk about this.
We have an outer function and then we call the outer function.
So the Python interpreter is going to go and say, all right, we have an X variable that is local to
the outer function.
And then inside of here, we going to define an inner function, another function.
And in here, before we even call that, we jumped in line nine and say, all right, call inner function.
We come back and we say, hey, line five, I want to use nonlocal X.
Hmm.
What does that mean?
Well, I want to use this X variable because it's nonlocal.
That is, I don't want to create a new X variable.
I want to jump up the scope to my parents, scope my parent local and grab whatever you find in there.
As long as it's not global variable any parent will do.
I want to grab that nonlocal.
So now this X is referring to the outer function here.
So when we say X equals nonlocal, we're assigning this new string.
And replacing this local so that when we print interacts, we get nonlocal, but also when we print
the outer X, we've modified this outer scope with the nonlocal keyword.
So that becomes nonlocal as well.
If I remove this line and let's comment it out and I click run.
You see the difference now we have the inner nonlocal, but then the outer local hasn't been modified
because this is a new variable.
Again, I argue that this actually makes your code more complicated than it needs to be.
So there are special cases where you might want to use this, but if you can try to make your code predictable,
where you can avoid using things like nonlocal and global, mind you, they are there for a reason because
they are useful in some situations.
With that said, keep in mind, make your code predictable, make your code clean, and I'll see you
in the next video.