Returning Values vs Modifying Global Variables
00:00 In this lesson, we’ll compare writing functions to return a value with writing functions to change a global variable. Before we look at changing global variables, we need to understand side effects with functions.
00:14 A side effect of a function is when a function has some observable behavior other than returning a value. Examples include printing something on the screen, changing the state of an object, writing data to a file, and modifying a global variable.
00:32 Remember, a global variable is a variable defined outside of any function. And these are just some examples of side effects. You’ll encounter others. But really, you don’t want to change a global variable, and we’ll take a look at why.
00:49 Why is modifying a global variable bad? Programs with functions that modify global variables are very difficult to debug and maintain. The place where a global variable is being changed may be written far away from other places where it’s used.
01:07 It’s often difficult to follow changes to a global variable. Related to that is the fact that other functions are using that global variable, and changes to that variable may impact other functions that rely on it.
Here’s an example of a global variable being changed. This isn’t being shown to you as something you should do, but you’re seeing it here so you can recognize it when you see it in other programs. We have a function
increment(), which is changing the global variable
counter defined at the very top of this code segment. Let’s take a look at this.
We’ll come back to this line in a moment, but basically we want to increment the
counter variable by
1. That second line there,
global counter—because you’re about to change a global variable, you must alert Python to your intent by declaring it as a global variable. We declare it saying
You don’t need to declare it if your function is just going to use a global variable, but since we’re changing it, we have to declare
global. There’s our function definition, and now we can use it.
03:31 It takes some arguments and returns the value, and most importantly, it doesn’t modify global variables. Everything the function interacts with comes in through the arguments, any variables that it creates, and finally its return value.
So we simply take the variable that we were given, add
1 to it, and return that new value. And then best practice is to call that function on the variable we wish to increment and then save the result back to that same variable name.
Become a Member to join the conversation.