Enrol to start learning
Reading is open to everyone. Enrolling is free, and it is what unlocks the audio lessons, practice tests and progress tracking.
3.4. global and nonlocal Keywords
Interactive Audio Lesson
Unlock the classroom podcast
The transcript is above and free to read. A free account plays the conversation back.
Create a free accountToday, 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.
Unlock the classroom podcast
The transcript is above and free to read. A free account plays the conversation back.
Create a free accountNow, 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.
Unlock the classroom podcast
The transcript is above and free to read. A free account plays the conversation back.
Create a free accountLet'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!
Overview
Short Summary
The global and nonlocal keywords in Python allow function-level access to variables defined outside their immediate scope.
Medium Summary
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 Summary
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:
x = 5
def change():
global x
x = 10
change()
print(x) # Output: 10In 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.
def outer():
x = 5
def inner():
nonlocal x
x = 10
inner()
print(x) # Output: 10
outer()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
Unlock the audio lesson
The script is above and free to read. A free account plays it back, in the voice you pick.
Create a free account• 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.'
Unlock the audio lesson
The script is above and free to read. A free account plays it back, in the voice you pick.
Create a free accountExample:
x = 5
def change():
global x
x = 10
change()
print(x) # Output: 10Detailed 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.
Unlock the audio lesson
The script is above and free to read. A free account plays it back, in the voice you pick.
Create a free account• 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.'
Unlock the audio lesson
The script is above and free to read. A free account plays it back, in the voice you pick.
Create a free accountExample:
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
Core takeaways and short definitions to help you quickly recall the key ideas from this section.
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
Step-by-step examples to apply the section's ideas and test your understanding.
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
Stories
Memory Tools
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.