3.4 - global and nonlocal Keywords
Enroll to start learning
Youβve not yet enrolled in this course. Please enroll for free to listen to audio lessons, classroom podcasts and take practice test.
Interactive Audio Lesson
Listen to a student-teacher conversation explaining the topic in a relatable way.
Understanding global Variables
π Unlock Audio Lesson
Sign up and enroll to listen to this audio lesson
Today, we'll explore how we can access and modify global variables using the global keyword. Can anyone tell me what a global variable is?
Isn't it a variable that can be accessed from anywhere in the program?
Exactly! A global variable is declared outside any function. Now, using the global keyword allows us to modify this variable inside a function. For example, if I have `x = 5` and I want to change it inside a function, I use the global keyword.
Could you give us an example?
Sure! Hereβs how it looks. *`x = 5` and then in the function, we write `global x; x = 10`. After calling the function, if we print `x`, it will show 10.*
I see! So, itβs about taking control over global variables from within a function.
Exactly! Remember: global variables are modified with the keyword where necessary.
So, if I miss `global` inside the function, I wonβt be able to change the global variable?
Correct! Without it, Python treats `x` as a local variable. Great question! Letβs summarize: You must declare global variables with the global keyword if you intend to modify them within a function.
The Nonlocal Keyword
π Unlock Audio Lesson
Sign up and enroll to listen to this audio lesson
Now, let's shift to the nonlocal keyword. This keyword is used in nested functions to modify a variable in the outer scope. Can someone explain what nested functions are?
They are functions defined inside another function, right?
Correct! With nested functions, we can use nonlocal to access variables from the enclosing function. For instance, if `y` is defined in the outer function, how might we change its value in the inner function?
By declaring it as nonlocal in the inner function?
Yes! Let's see an example together. In the outer function, we define `y = 10` and then in the inner function, we write `nonlocal y; y = 20`. After calling the outer function, it prints the updated value of `y`.
So, using nonlocal allows us to modify the variable defined in the outer function's scope?
Precisely! This is vital when you want to retain the context of your variables in closures. To wrap up: nonlocal helps in modifying non-global variables in outer functions.
Scope and Modifying Behavior
π Unlock Audio Lesson
Sign up and enroll to listen to this audio lesson
Let's discuss the implications of using global and nonlocal. Why do you think we might want to avoid using global variables unnecessarily?
They can create confusion about the state if many functions modify them?
Exactly! Overuse of global variables can lead to hard-to-trace errors. It's often regarded as better practice to keep them to a minimum!
And what about nonlocal? Are there pitfalls we should watch for?
Great question! Nonlocal can also introduce complications, especially with larger nested structures. If not handled carefully, modifying outer variables can lead to unintended side effects.
So, handling variables well is essential for code readability and maintainability!
Absolutely! Keeping scope considerations in mind helps in writing clean and manageable code. To summarize, be cautious with global & nonlocal to maintain clarity in your code!
Introduction & Overview
Read summaries of the section's main ideas at different levels of detail.
Quick Overview
Standard
This section discusses the significance of the global and nonlocal keywords in Python. The global keyword modifies global variables within functions, while the nonlocal keyword enables access to variables defined in enclosing (but not global) scopes, typically used in nested functions. Understanding these keywords is vital for managing variable scope effectively.
Detailed
Global and Nonlocal Keywords in Python
In Python, scope defines where variables are accessible and can vary based on how and where they are defined. The global keyword is utilized within a function to indicate that a variable is defined at the module level. This allows functions to modify global variables directly. For example:
In the example above, the change function modifies the global variable x, which is initialized with the value 5.
On the other hand, the nonlocal keyword is pertinent in nested functions, allowing them to modify variables defined in the outer function's scope without directly accessing global variables. This is crucial when dealing with closures where you want to preserve or modify the state of outer function variables.
In summary, understanding these keywords is essential for effective variable management within different scopes and to ensure the correct modification of variable values in structured Python programs.
Audio Book
Dive deep into the subject with an immersive audiobook experience.
The Global Keyword
Chapter 1 of 4
π Unlock Audio Chapter
Sign up and enroll to access the full audio experience
Chapter Content
β’ global: Used to modify global variables inside a function.
Detailed Explanation
The global keyword is used in Python functions to declare that a variable inside the function refers to a variable that exists outside of the function's scope. If you want to change the value of a global variable from within a function, you must specify that it is global using the keyword global. This informs Python to use the existing global variable instead of creating a new local variable with the same name.
Examples & Analogies
Imagine you have a box (the global variable) that you store items (data) in, and you sometimes need to access this box from multiple rooms (functions) in your house (program). If you want to change the contents of the box from one of the rooms, you need to point specifically to the actual box in the living room rather than creating a new smaller box just for that room. Using 'global' is like saying, 'I want to refer to the box in the living room, not create my own smaller box here.'
Example of Using the Global Keyword
Chapter 2 of 4
π Unlock Audio Chapter
Sign up and enroll to access the full audio experience
Chapter Content
Example:
x = 5
def change():
global x
x = 10
change()
print(x) # Output: 10
Detailed Explanation
In this example, we start with a global variable x initialized to 5. The function change() uses the global keyword to indicate that x refers to the global variable. Inside the function, x is set to 10, which changes the global variable's value. After calling change(), when we print x, it will output 10 instead of 5 because the global variable was modified inside the function.
Examples & Analogies
Think of this as changing the number of cookies in a jar (global variable) located in the kitchen. By saying, 'I want to change the cookie count in the kitchen jar', you are ensuring that everyone accessing the kitchen jar will see the updated count of cookies instead of just a few cookies stored in a personal bag (local variable) in your room.
The Nonlocal Keyword
Chapter 3 of 4
π Unlock Audio Chapter
Sign up and enroll to access the full audio experience
Chapter Content
β’ nonlocal: Used in nested functions to modify a variable in the outer (non-global) scope.
Detailed Explanation
The nonlocal keyword is used in nested functions to indicate that a variable should not be considered local to the inner function, but instead refers to a variable in the nearest enclosing scope that is not global. This is important when you want to modify a variable defined in an outer function's scope from within a nested function.
Examples & Analogies
Imagine you have a multi-story house where you store items in different rooms (functions). If you want to access an item stored in a storage room (the outer function) from a bedroom (the nested function), you can use nonlocal to say, 'Please refer to the storage room for this item instead of thinking Iβm putting it in this bedroom.'
Using the Nonlocal Keyword Example
Chapter 4 of 4
π Unlock Audio Chapter
Sign up and enroll to access the full audio experience
Chapter Content
Example:
def outer_function():
x = 5
def inner_function():
nonlocal x
x = 10
inner_function()
print(x) # Output: 10
outer_function()
Detailed Explanation
In this code, outer_function defines a variable x with the value 5. The inner_function, which is nested inside the outer function, uses the nonlocal keyword to indicate that the x it refers to is from the enclosing scope, i.e., outer_function. When inner_function is called, it modifies x to be 10. When we print x from the outer_function, it reflects the updated value of 10.
Examples & Analogies
Think of this like a family decision-making process across multiple generations. If a grandparent (the outer function) wants to change something that affects the whole family but invites their children (the inner function) to help with the decision, using nonlocal ensures that any changes they discuss refer back to the original family agreement rather than creating a new rule just for the children.
Key Concepts
-
Global Variable: A variable that can be accessed from anywhere in the program.
-
Global Keyword: Used to modify a global variable inside a function.
-
Nonlocal Variable: A variable found in an enclosing scope, allowing nested functions to modify it.
-
Nonlocal Keyword: Declares a nonlocal variable in a nested function.
-
Scope: Defines the accessibility area of a variable.
Examples & Applications
Using global:
x = 5
def change():
global x
x = 10
change()
print(x) # Output: 10
Using nonlocal:
def outer():
x = 5
def inner():
nonlocal x
x = 10
inner()
print(x) # Output: 10
outer()
Memory Aids
Interactive tools to help you remember key concepts
Rhymes
Global is wide, reaches far and near, inside functions, it's the keyword we hold dear.
Stories
Once in a function village, there was a global river that everyone could access. But in a small nested forest nearby, only the nonlocal paths knew how to adjust the small creek's flow.
Memory Tools
G-N for the keywords: G for global for the overarching access, N for nonlocal for deeper-nested scope changes.
Acronyms
Remember LEGB
Local
Enclosing
Global
Built-in
the order Python uses to resolve variable names.
Flash Cards
Glossary
- Global Variable
A variable that is defined outside any function and can be accessed from anywhere in the code.
- Global Keyword
A keyword used to declare a global variable inside a function.
- Nonlocal Variable
A variable that is defined in an enclosing function and can be accessed or modified in nested functions.
- Nonlocal Keyword
A keyword used to declare a nonlocal variable in a nested function.
- Scope
The region in the code where a variable is accessible.
Reference links
Supplementary resources to enhance your learning experience.