Industry-relevant training in Business, Technology, and Design to help professionals and graduates upskill for real-world careers.
Fun, engaging games to boost memory, math fluency, typing speed, and English skillsβperfect for learners of all ages.
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 mock test.
Listen to a student-teacher conversation explaining the topic in a relatable way.
Signup and Enroll to the course for listening the Audio Lesson
Today, 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.
Signup and Enroll to the course for listening the Audio Lesson
Now, 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.
Signup and Enroll to the course for listening the Audio Lesson
Letβ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.
Read a summary of the section's main ideas. Choose from Basic, Medium, or Detailed.
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.
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.
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 print
and len
.
To resolve variable names, Python applies the LEGB ruleβLocal, Enclosing, Global, and Built-in, determining the order of scope resolution.
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.
Dive deep into the subject with an immersive audiobook experience.
Signup and Enroll to the course for listening the Audio Book
Scope 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).
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.
print
and len
, which are available anywhere in your code.
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.
Signup and Enroll to the course for listening the Audio Book
Python resolves variable names using the LEGB rule:
- L β Local
- E β Enclosing
- G β Global
- B β Built-in
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:
1. Local: First, it checks if the variable is defined in the current function (local scope).
2. Enclosing: If it doesn't find it, it looks for the variable in any enclosing functions, moving outward.
3. Global: Next, it checks the global scope to see if the variable is defined outside of all functions.
4. Built-in: Finally, if it still can't find the variable, it looks for predefined built-in functions.
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.
Signup and Enroll to the course for listening the Audio Book
Global Variable Example:
Local Variable Example:
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 = 10
is a global variable and can be printed inside the display()
function.
- Local Variables are defined within a function and can only be accessed within that function. In the func()
example, x
is local, and trying to print x
outside of func()
will raise an error since x
doesn't exist in the global scope.
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.
Signup and Enroll to the course for listening the Audio Book
β’ 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:
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 global
keyword. In the example, x
is made a global variable inside the change()
function, allowing it to update x
to 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.
Think of global
and nonlocal
keywords like different types of permissions:
- The global
keyword 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 nonlocal
keyword 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).
Learn essential terms and foundational ideas that form the basis of the topic.
Key Concepts
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.
See how the concepts apply in real-world scenarios to understand their practical implications.
Global Variable Example: x = 10
followed by a function that prints x
shows using global variables.
Local Variable Example: Within a function, if x = 5
is defined, and print(x)
outputs 5
.
Use mnemonics, acronyms, or visual cues to help remember key information more easily.
In local bounds, the data stays, in global reach, it freely plays.
Once there was a global variable named x
who wanted to join the local functions. But, without the magic word global
, it could never truly belong!
Remember LEGB - Local begins, Enclosing around, Global to see, Built-in's always found!
Review key concepts with flashcards.
Review the Definitions for terms.
Term: Scope
Definition:
The region of a program where a variable or function is accessible.
Term: Local Scope
Definition:
The scope of variables defined within a function.
Term: Global Scope
Definition:
The scope of variables defined outside any function; accessible globally.
Term: Enclosing Scope
Definition:
The scope of variables in an outer function when using nested functions.
Term: Builtin Scope
Definition:
The scope of names that Python has predefined, such as built-in functions.
Term: LEGB Rule
Definition:
The ordering of scope resolution: Local, Enclosing, Global, Built-in.
Term: Global Variable
Definition:
A variable defined outside all functions that can be accessed globally.
Term: Local Variable
Definition:
A variable defined within a function, not accessible outside that function.
Term: Nonlocal Keyword
Definition:
A keyword used to work with variables in the nearest enclosing scope, not global.
Term: Global Keyword
Definition:
A keyword that allows a function to modify a global variable.