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. Scope and Lifetime of Variables
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 will discuss scope. Can anyone tell me what scope refers to in programming?
Isn't it about where you can use a variable in your code?
Exactly! Scope defines where a variable is accessible. It can be local, global, enclosing, or built-in. Who can give me an example of a local variable?
A variable that is defined inside a function, right?
But what about a global variable?
Great question! A global variable is defined outside any function and can be accessed anywhere in the code. Let's remember the acronym LEGB: Local, Enclosing, Global, Built-in. It helps us recall the order in which Python checks the scope!
So if I have both a global and local variable with the same name, which one does Python use?
Python will prioritize the local variable over the global one in that scope. Now, can anyone summarize what we've learned about scope?
Scope is about where variables can be used, and there are different types!
Exactly! Well done, everyone.
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 dive deeper into the LEGB rule. Can someone explain what it stands for?
It stands for Local, Enclosing, Global, Built-in.
Correct! This order is crucial for how Python resolves variable names. If we create a variable named x inside a function, can we access the global x from within that function?
Not unless we use the global keyword, right?
That's right! The global keyword tells Python that the variable we want to use is defined globally. Let’s recap—local variables are checked first, then variables in enclosing functions, followed by global variables, and finally built-in names. Can someone provide an example of when this might matter?
If I have a local variable x and I want to change the global x, I'll need to use global x.
Exactly! Remembering the LEGB hierarchy helps in understanding scope resolution.
Unlock the classroom podcast
The transcript is above and free to read. A free account plays the conversation back.
Create a free accountLet’s now look at an example with global and local variables. If I define x = 10 globally and then create a function that defines x = 5, what do you think happens if I try to print x inside the function?
It will print 5 because the local x takes precedence.
Exactly, now if I want to change the global x to 20 inside the function, what keyword would I use?
You would use the global keyword, right?
Correct! And if we had a nested function that needed to access a variable from a non-global outer function, which keyword would you use?
Nonlocal?
Yes! The nonlocal keyword allows access to a variable in the nearest enclosing scope. Let’s summarize: global variables can be accessed anywhere, local variables can only be accessed in their function, and global and nonlocal keywords help manage scope.
Overview
Short Summary
This section discusses the concept of scope in programming, focusing on where variables can be accessed within a program based on their lifetime and defined regions.
Medium Summary
The section elaborates on the different types of variable scope—local, global, enclosing, and built-in—along with the rules governing their accessibility. It also highlights the usage of keywords like 'global' and 'nonlocal' to manipulate variable scope effectively.
Detailed Summary
Scope and Lifetime of Variables
This section delves into the concept of scope, which dictates where in the program a variable can be accessed. Understanding scope is crucial for avoiding errors and writing efficient code.
Types of Scope
The different types of variable scope include:
- Local Scope: Variables defined within a function.
- Global Scope: Variables defined outside any function.
- Enclosing Scope: Variables in an outer function when using nested functions.
- Built-in Scope: Predefined variables that Python recognizes, such as
printandlen.
LEGB Rule
To resolve variable names, Python applies the LEGB rule—Local, Enclosing, Global, and Built-in, determining the order of scope resolution.
Global and Local Variables Example
A global variable retains its value across the program, while a local variable exists only within its function. This section uses examples to illustrate how global variables can be accessed and modified, with explanations of the 'global' and 'nonlocal' keywords which help in altering their scope effectively.
By mastering scope and variable lifetimes, programmers can craft clearer, more efficient, and bug-free code.
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 accountScope refers to the area of the program where a variable is accessible.
Types of Scope:
- Local Scope: Variables defined inside a function.
- Global Scope: Variables defined outside any function.
- Enclosing Scope: Variables in the outer function in nested functions.
- Built-in Scope: Names preassigned in Python (like print, len).
Detailed Explanation
Scope in programming is simply the region in a code where a variable can be accessed or used. It tells you where the variable can 'live' and be meaningful.
- Local Scope: This is for variables created within a function. They are only known within that function.
- Global Scope: Variables that are defined outside functions can be accessed from anywhere in the code.
- Enclosing Scope: This is relevant when you have nested functions - a variable defined in an outer function can be accessed by an inner function.
- Built-in Scope: These are the functions and names that Python has pre-defined, like
printandlen, which are available anywhere in your code.
Examples & Analogies
Imagine a school:
- Local Scope is like a classroom where only the students inside that classroom can use the materials and resources available there.
- Global Scope is like the entire school where any student can access the library books anywhere within the school.
- Enclosing Scope could represent a situation where you have a school district (outer function) where multiple schools (inner functions) can access some resources shared by the district, but they cannot access each other's school-specific resources.
- Built-in Scope is like the school's infrastructure that everyone uses, such as classrooms, halls, and restrooms.
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 accountPython resolves variable names using the LEGB rule:
- L – Local
- E – Enclosing
- G – Global
- B – Built-in
Detailed Explanation
The LEGB rule is a hierarchy Python follows when searching for variables. When you use a variable, Python looks for it in the following order:
- Local: First, it checks if the variable is defined in the current function (local scope).
- Enclosing: If it doesn't find it, it looks for the variable in any enclosing functions, moving outward.
- Global: Next, it checks the global scope to see if the variable is defined outside of all functions.
- Built-in: Finally, if it still can't find the variable, it looks for predefined built-in functions.
Examples & Analogies
Think of the LEGB rule like a hierarchy in a business:
- Local would be an employee that looks for resources only within their department (local scope).
- Enclosing would be an employee asking their direct manager (enclosing function) if resources are available in that department.
- Global would be reaching out to the company's main office (global scope) where larger resources are managed.
- Built-in would be checking the company handbook (built-in scope) for standard procedures that everyone can access.
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 accountGlobal Variable Example:
x = 10
def display():
print(x)
display()
Local Variable Example:
def func():
x = 5
print(x)
func()
print(x) # This will give an error if x is not defined globallyDetailed Explanation
In programming, variables can be classified as global or local based on where they are defined:
- Global Variables are defined outside functions and can be accessed from any place in the program. In the example,
x = 10is a global variable and can be printed inside thedisplay()function. - Local Variables are defined within a function and can only be accessed within that function. In the
func()example,xis local, and trying to printxoutside offunc()will raise an error sincexdoesn't exist in the global scope.
Examples & Analogies
Imagine a public library as a Global Variable where everyone can access the books from anywhere. In contrast, a specific book in a school's classroom (Local Variable) can only be used by the students in that classroom. If someone outside the classroom tries to get that book, they won't be able to find it.
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. • nonlocal: Used in nested functions to modify a variable in the outer (non-global) scope.
Example:
x = 5
def change():
global x
x = 10
change()
print(x) # Output: 10Detailed Explanation
In Python, you can modify variables from different scopes using two keywords:
- global: When you want to change the value of a global variable inside a function, you use the
globalkeyword. In the example,xis made a global variable inside thechange()function, allowing it to updatexto 10. - nonlocal: This keyword is used in nested functions to indicate that you want to use a variable from an enclosing (but not global) scope. This is important when you intend to modify variables in a parent function from a child function.
Examples & Analogies
Think of global and nonlocal keywords like different types of permissions:
- The
globalkeyword is like a child who is given permission by their parent (the function) to use the family car (the global variable) for any errand. - The
nonlocalkeyword is like a student being allowed to modify a project that is shared by their school club (the outer function) while they are working in a specific group (the inner function).
--
Key Concepts
Core takeaways and short definitions to help you quickly recall the key ideas from this section.
Scope: Defines where in a program a variable is accessible.
Local Scope: Information related only to the function in which it is defined.
Global Scope: Variables can be accessed from anywhere in the program.
LEGB Rule: The order of scope resolution in Python.
Global and Nonlocal Keywords: Tools for modifying variables in different scopes.
Examples
Memory Aids
Interactive tools to help you remember key concepts
Stories
Memory Tools
Flash Cards
Glossary
Scope
The region of a program where a variable or function is accessible.
Local Scope
The scope of variables defined within a function.
Global Scope
The scope of variables defined outside any function; accessible globally.
Enclosing Scope
The scope of variables in an outer function when using nested functions.
Builtin Scope
The scope of names that Python has predefined, such as built-in functions.
LEGB Rule
The ordering of scope resolution: Local, Enclosing, Global, Built-in.
Global Variable
A variable defined outside all functions that can be accessed globally.
Local Variable
A variable defined within a function, not accessible outside that function.
Nonlocal Keyword
A keyword used to work with variables in the nearest enclosing scope, not global.
Global Keyword
A keyword that allows a function to modify a global variable.