Function Scope
Learn about variable scope, global variables, and what happens when we pass mutable and immutable variables as function parameters.
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:
def func():name = "Stark"func()print(name) # Accessing 'name' outside the function
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.
name = "Ned"def func():name = "Stark"func()print(name) # The value of 'name' remains unchanged.
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: ...