< previous | Table of Contents | next > |
4.3 VARIABLE SCOPE
Variables are classified into two main types—local and global—based on their scope, which determines where they are accessible within the code.
LOCAL VARIABLES
Local variables are declared inside a function or block and are only accessible within that function or block. They are created when the function starts execution and destroyed when it completes its purpose. Each call to the function creates new local variables, and changes to local variables in a function do not affect variables with the same name outside the function. Local variables are used to store only relevant data within the context of a function or block.
def function(): local_var = 5 # Local variable, accessible only within 'function' print(local_var) function() print(local_var) # This would raise an error because local_var is not accessible outside the function
Here's an example in Thonny of what would happen when you try to access a local variable outside of its defined function.
GLOBAL VARIABLES
Global variables are declared outside any function and can be accessed anywhere in your source code. To modify a global variable inside a function, you must declare it global using the global keyword; otherwise, Python will treat it as a local variable.
However, note that global variables should be used with caution as they can make your code more complex to understand and debug. It can also cause unintended behavior as you manipulate the variable throughout the source code within functions, etc., and it's easy to lose track. So, in most cases, you should avoid using global variables.
global_var = 10 # Global variable, accessible anywhere in the source code def function(): global global_var global_var += 1 # Modifying the global variable print(global_var) function() # Calling the function print(global_var) # Accessing the modified global variable outside the function
Here we can see that we're able to access the global variable both within outside and inside the function. Below is an example in Thonny of what such a program would output.
KEY THINGS TO REMEMBER
- Local variables are declared within a function or block and can only be accessed within that specific function or block.
- Global variables are declared outside any function or code block and available throughout the source code.
- Limit global variables as they can make the program difficult to debug and maintain due to their potential to be modified from anywhere in the program.
SELF-CONTROL EXERCISES
< previous | Table of Contents | next > |