Python Scope tutorial for Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello and welcome I'm Dave today we will learn about scope in Python and I'll provide links to all resources in the description below I've got vs code open you can see I have a lesson 11 folder open over here currently no files let's go ahead and create a new python file and we'll call this scope dot Pi there are different types of scope and the first one we want to learn about is the global scope so when I Define a variable like name and set it equal to Dave this is in the global scope because this will be available to everything in this file so if I save this and then I go ahead and print name of course it's available so let's add something else here to compare to the global scope so now I'll Define a function and I'll call this greeting and then greeting will accept a name parameter as well and now inside of this function I will print name now of course this parameter has the same name but it's not referring to the same thing this is a parameter for the function so it's going to print whatever I pass in but let's go ahead and Define something else like well instead of name actually let me think about this differently let's first prove that we can print this name value because this is in the global scope but being in the global scope it's also available inside of this function but this function has a local scope so let's go ahead and do this first I'll save this and then of course we need to call our greeting function for it to run and let's put an extra space because it likes to scroll up when I save so we'll go ahead and save that and now I'm going to come over here to the drop down menu and choose run python file and we've got this here at the bottom and it prints Dave so it printed the value of name now we defined name in the global scope like I said the function has a local scope as well so we'll look at that but right now I want to move this over to the right so I'm going to go to view and from view I'm going to go to appearance and then from appearance I'm going to go to panel position and choose right instead of bottom so now we can see our output here on the right and I've got Dave as the output there when we first ran our code so now let me Define another variable but I'll Define it inside of the function so I'm going to say color equals blue but now if I try to print that outside of the function I'm going to try to print color look vs code gives it a squiggly Mark and if I Mouse over color it says color is not defined that's because color is in the local scope of the function and it's only available here if I want to print color inside of the function BS code is going to have no problem with that because it knows what color is inside of this local scope but out here outside of the function in the global scope it does not know what color is so let's go ahead and remove this print color in the global scope because that would cause an error but if we run the function now we should see the value of color and the value of names so I'll run the code again and we get blue and Dave and that's because this function inside of its local scope can access the global scope and get the value of name and it also has access to its own local scope and it gets the value of color now let me go back to what I was going to do and I'll pass in a parameter here for the function and I could name it the same thing as name or I could name it something else like first name and it would be the parameter and so I'll do that just to eliminate some confusion so we'll print first name now so when we call this we would be calling it with a name like John and then of course we could still print name inside of here and the local scope of the function should still be able to access the value of name but it can also get a value from the parameter name so let's go ahead and do this first and we'll run the code and now we get blue Dave John but what if this had the same name so now I'm getting back to where I first started and now name is a parameter so I can remove one of these prints because we're just doubling that up and so this does not represent the value that's in the global scope name now represents the parameter that the function is receiving so now if we run the code we get blue and John because we passed in John so when dealing with variables I hope this eliminates any confusion where we can see there is a local scope inside of functions and yet there is a global scope that's available outside of functions and outside of anything else that the value may be in so if it's defined outside of anything else it's in the global scope which can be accessed inside of functions but if we Define it inside of a function where the local scope is it cannot be accessed outside of the functions now this not only applies to variable names but it also applies to functions so let me create another function and I will call this another and that's just because I couldn't think of anything else and inside of another we're going to go ahead and call our greeting function and here I'll pass in Dave so now we'll need to call another down here at the bottom so we'll put the another call at the very bottom of the file and now let's run this code again remember we're already running it here with John and then we're going to run it here and it doesn't need to receive a parameter it's just going to run greeting with Dave so now let's run the code and you can see we get blue John blue Dave so we can call one function inside of the local scope of another function and that's because this function greeting was defined in the global scope so it's available to be called inside of the local scope of another function so as you might guess we can also Define functions inside of other functions so let's go ahead and do that I will control X to remove greeting here and put it inside of another before we call it and now it doesn't like the definite edition of color being blue right here and it doesn't like the call to greeting because this is in the global scope and now the function is being defined inside of the local scope of another so we could only call this function inside of this another function but the reason it doesn't like the definition of blue is because these are not indented properly for the definition of greetings so let's just tab that over because remember the spaces in Python do matter so as we tab this over this indicates the local scope of greeting so what if we put color inside of the another scope and now it should still be accessible inside of greeting because this is the parent scope so what we have here is a nested function and the parent function is another it's defined in the global scope and then we're defining the color blue inside of the local scope of another and then we're defining the function greeting which makes the function greeting only available inside of the local scope of another so it's not available out here and even if we put it after our function definition here it's still going to have a problem because it's not defined in the global scope so let's remove that however I'll get rid of some of these spaces here too however inside of another we can call gradients so there is no problem here so let's go ahead and save this code and we'll run this code and see what we get and we get blue and Dave and that's because we defined the color here inside of the another local scope then we Define the function and greeting inside of the another local scope and then we called greeting and greeting prints the color and prints the name so understanding scope applies both to variables and to functions and you can have nested function definitions if you're wondering why you would actually have a nested function well that could be because you're only going to use the function inside of the other function and therefore it doesn't need to be defined outside of the function now if we did Define greeting outside of the function as we did earlier you saw that I could call greeting inside of another function still because it was in the global scope and then the other function another still has access to that greeting function so it's a decision at design time really where you define your function but if it's only going to be useful inside of this function you can just Define it inside of here because there's something called polluting the global scope and you really don't want to put anything in the global scope that you really don't have to because that can make things more confusing later on especially if you're working on a team with other developers so we try to keep the global scope as unpolluted or with as few things as possible and we try to put everything else inside of functions or later we'll learn about classes and objects and so on but that is important to understand about scope so we have a global scope and the local scope and it applies both to variables and to functions now one more thing we haven't looked at is what if we want to modify the assignment of a variable inside of a function but the variable was initially defined in the global scope so let's put a another variable out here and I'll just call this count and set it equal to one so this is a global variable and now if I try to Define count inside the function so I'll say count equal to 2 and then let's go ahead and print count right here inside of the parent function so we'll print count let's see what we get as far as the output goes so I'm going to go ahead and run the code and we get two that's because we really created another variable here we didn't reassign count that's because we can't reassign that that easily so we need to use the global keyword but notice if we do what happens is we have an error here we can't just do this all in one line so Global count so another way I could of course demonstrate this instead of saying count equals 2 is we're trying to take the previous value so let's say count plus equals one and now let's see what value we get and this should show that I'm not using the value from count because if I use this Global value then it would be equal to 2 correct let's see what we get and we do get an error says Unbound local error cannot access local variable count where it's not associated with a value that's because it doesn't currently have a value there so we can't really do that now of course we said we can go ahead and access the value of count if we're not trying to modify it there is no problem so if I run the code now we get one that's because it gets the value from the global variable but trying to modify this inside of the function when it's already defined here but we didn't give it a definition because this would be a new variable essentially if we were just trying to assign another number to it like one or previously I had two this is just creating another variable named count in the local scope and I know that can sound confusing but that's what it is doing so really what we need to do is use the global keyword and now we'll say Global count equals plus equals one so we're adding 1 to that but we can't do that all on the same line so then we need to go ahead and just say Global count on one line and then say count plus equals one now it's going to go ahead and be happy about that so now we'll run the code again and you can see we get 2 because it added 1 to the value of the global count but we had to use that keyword before we could modify the global value so I know that may be a little difficult to wrap your head around at first but what you need to understand is that if you just assign count inside of this another function's local scope you're essentially creating a new variable named count and you're assigning a value to it now if you try to modify count because it already exists so if we didn't have this Global here and we were just trying to modify that is when we got the error because yes it knows count exists and you're trying to modify it before or you've used the global keywords so now by using Global count and then modifying it everything was okay now in nested functions the same concept exists and especially if we're trying to modify a value that was defined in a parent function inside of a nested function like color equals blue well then there's another keyword we need to use and that is non-local so we'll say non-local color and that tells our greeting function that it's going to be using the color from the parent function and from there we can assign color equal to red and it should be okay but of course this looks just like reassignment so if we didn't have this we would essentially once again be creating a new color variable vs code helps us see this because we're not printing color like we are here inside of another so look at how this is now grayed out because it knows we're not using the value of this variable and this is a different variable at this point then color is inside of the greeting but once we uncomment our non-local color then vs code knows we're using this color variable and then we're just reassigning it here so I'll once again save and run the code just so we can see everything and we have two red and Dave okay let's close our output window for now and in the file tree let's go ahead and create a new file I'm going to call this rps4 dot Pi now I'm just going to pull in the rock paper scissors code from the previous lesson where we had a file named rps3 so if you have that you may want to open that up I'm just going to paste this in so we have that same code to work with so now at the very top of the file let's go ahead and create one Global variable and I'll call this game underscore count and set it equal to zero now in a future modification we will remove the global variable once again because I said it's important to not use Global variables where they're not needed and we will be able to remove this in a future iteration of this game but for now we're going to put a global variable here called game underscore count and set it equal to zero now let's scroll down to once we get past the decision tree here but before the play again in our code get a little bit of space and then we'll tab in to line it up and let's go ahead and say Global game underscore count so now we're telling the function we're going to work with and modify that game Count variable that's in the global scope inside of the local scope of the function and we'll set game count and then we'll say plus equals one so we're counting how many games we've played and then before we ask play again we can print and we'll start with a slash in for a new line and then we'll say game count give a colon and then of course we have our quote here and then we'll just say plus and we'll make sure this is a string now as we print this out or we would get an error so we will use our string here to convert this to a string Str and then we'll put the game count so this should output how many times we've played the game and even though we run the function again and again it won't lose the count because that counts not stored in the function it's stored in the global scope outside of the function now one other thing we could apply that we have learned today is a nested function so let's do that with this game winner decision here so I'm going to tab in and then say Def and I'll call this decide wide underscore winner as a function it's going to receive the player as a param and the computer as a param now inside of the function I'll need to tab all of this over so I'll highlight all of this and press tab then we're going to change this a little bit because instead of the print here I'm going to select print the first parentheses and then I'm going to go ahead and press Ctrl D to select the next the next the next and the next and I'm going to change this to the keyword return because it's a function so then likewise I'm going to select the last quotation and the closing parentheses Ctrl D again as I select all of those then just a right arrow to make sure I'm at the end and then backspace once and we've changed all of those at once and now we have a decide winner function that is going to return the appropriate response based on the decision but now we need to add a couple of more lines but because we haven't called this function now decide winner is our nested function that's inside of our function up here called play RPS so underneath decide winner now we're going to go ahead and say game result which is a new function is going to equal decide winner and we're going to pass in the values we have for player and computer so it's important to know with the parameters even though I named those parameters the same so I wouldn't have to rename all of these they could be named differently because here these hold values player and computer from above however here player and computer are params inside of the function they represent whatever value we pass into that function so we're calling decide winner and we're storing whatever is returned inside of game result so then we need to go ahead and print game underscore result to see that output okay with these changes in place let's go ahead and run our code by choosing run python file and now it's asking us to play the game I'm going to choose Rock and it says python wins our game count is one do we want to play again sure so why let's go ahead and choose paper and i1 so game count is two play again and you can see how the game count is working we'll choose three and hey we won again so game count is three so that's working as expected everything else is working just like it was before but we created a nested function inside of our game as well so I hope today's lesson has helped you understand a bit more more about global scope and then local scope as we see inside a function remember to keep striving for Progress over Perfection and a little progress every day will go a very long way please give this video a like if it's helped you and thank you for watching and subscribing you're helping my channel grow have a great day and let's write more code together very soon
Info
Channel: Dave Gray
Views: 6,274
Rating: undefined out of 5
Keywords: python scope tutorial for beginners, python scope, python, scope, global scope, local scope, global scope in python, python global scope, local scope in python, python local scope, global vs local scope, global scope vs local scope, global keyword, python global keyword, global keyword in python, nonlocal keyword, nested functions, variable scope, python variable scope, variable scope in python, python tutorial for beginners, python tutorial, python for beginners, python tut
Id: e_UgAqOdEXY
Channel Id: undefined
Length: 19min 49sec (1189 seconds)
Published: Tue Apr 25 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.