Scope
What Is Scope?
- Scope defines where a variable can be accessed in your program. It's about the region within which the variable is recognized.
Types of Scope:
- Local Scope:
- A variable created inside a function is local and can only be used within that function.
Example:
pythondef myfunc(): x = 300 print(x) myfunc() # Output: 300
- Function Inside Function:
- Local variables are accessible to inner functions within the same outer function.
Example:
pythondef myfunc(): x = 300 def myinnerfunc(): print(x) myinnerfunc() myfunc() # Output: 300
- Global Scope:
- A variable created outside of a function is global and can be accessed by any function in the program.
Example:
pythonx = 300 def myfunc(): print(x) myfunc() # Output: 300 print(x) # Output: 300
Naming Variables:
- Using the same variable name inside and outside of a function will treat them as two separate variables.
Example:
pythonx = 300 def myfunc(): x = 200 print(x) myfunc() # Output: 200 print(x) # Output: 300
Global Keyword:
- Used to create or modify global variables inside a function.
Example:
pythondef myfunc(): global x x = 300 myfunc() print(x) # Output: 300To change a global variable inside a function:
pythonx = 300 def myfunc(): global x x = 200 myfunc() print(x) # Output: 200
Nonlocal Keyword:
- Used to work with variables inside nested functions, making the variable belong to the outer function.
Example:
pythondef myfunc1(): x = "Jane" def myfunc2(): nonlocal x x = "hello" myfunc2() return x print(myfunc1()) # Output: hello
Exercises:
- Local Scope Exercise:
- Write a function that creates a local variable and prints its value.
- Global Scope Exercise:
- Create a global variable and write two functions that print and modify its value.
- Using Global Keyword:
- Modify a global variable inside a function using the global keyword.
- Nonlocal Keyword Exercise:
- Write a nested function where the inner function modifies a variable from the outer function using the nonlocal keyword.
Summary:
- Understanding scope is crucial for managing variables and their accessibility within your code. Practice using local, global, and nonlocal scopes to get comfortable with variable management in Python!