The Scope of Variables
Global and Local Variables, and the global keyword.
Let’s first talk about variables
Variables are like a suitcase. They store different data types like strings and lists. They help us in our everyday lives. They store data types, so you can use them later. Instead of printing the same long string 20 times, you can just store the string in a variable. That will save time, and you won’t have to write the long string over and over again. But what if I tell you that there are 2 types of variables. What! The 2 types of variables are global and local variables
This is an example of global and local variables. Global variables are variables that are outside the function like global_var. Local variables are variables that are in the function like local_var.
This is an example of the global keyword. It uses the global variable, global_var. It uses global_var inside the function. So, when you print global_var, you won’t get an error. Since you are using the global function, you are telling the program that I am going to be using this variable in my function. Instead, it will print the value of global_var.
That is all about the scope of variables.