Function Scope
Explore Python function scope to understand where variables live and how their accessibility works within and outside functions. Learn the distinction between local and global variables, how to modify global variables safely, and how mutable and immutable data types behave inside functions to write clearer and more maintainable code.
We'll cover the following...
The scope of a function means the extent to which the variables and other data items made inside the function are accessible in code. In Python, the function scope is the function’s body. Whenever a function runs, the program moves into its scope. Once the function has ended, it moves back to the outer scope.
Data lifecycle
In Python, data created inside the function cannot be used from the outside unless it is being returned from the function. Variables in a function are isolated from the rest of the program. When the function ends, they are released from memory and cannot be recovered.
The following code will never work:
As we can see, the name variable doesn’t exist in the outer scope. Similarly, the function cannot access data outside its scope unless the data has been passed in as an argument or it is in the global scope.
Global scope
Global scope refers to the area of a program where variables that are defined outside of all functions exist. These variables are accessible from any part of the program, including inside functions, making them globally available. The global scope is the “top-most” scope in a Python program, and variables defined in this scope are known as global variables.
Here are some key points about global scope: ...