SlideShare a Scribd company logo
Python Scope
Web Developer-Python 1
Web Developer-Python
Error/ Warning Information Flashback Class Exercise
2
Web Developer-Python
AGENDA
1. Global, local variables
2. Nonlocal variable
3. Global keywords and namespaces
3
Web Developer-Python
1. Global, Local Variables
4
Web Developer-Python
Global, Local variables
Scope
 In Python, scope refers to the region or context in a program where a variable or a function is accessible.
 It defines the visibility and lifetime of a variable.
 Python uses a system of nested scopes, where each level has access to variables defined in its own scope and
those in its parent scopes, but not in its child scopes.
5
Web Developer-Python
Global, Local variables
The LEGB Rule
 Local(L), Enclosing(E), Global(G) and Built-in(B).
 The LEGB rule in Python is a hierarchy that the interpreter follows to resolve the names of variables.
 It stands for Local, Enclosing, Global, and Built-in.
 This rule helps Python determine the scope of a variable and which value to use when there are multiple
definitions of the same name in different scopes.
6
Web Developer-Python
Global, Local variables
Types of scope
1. Local scope
2. Global scope
3. Enclosing scope
4. Built-in scope
7
Web Developer-Python
Global, Local variables
Local scope
 Local scope refers to the region within a function where the variables and names defined are accessible.
 Variables created inside a function are said to be in the local scope of that function.
 These variables are only available within the function where they are created and cannot be accessed outside of it.
8
Web Developer-Python
Global, Local variables
Local scope
Characteristics of local scope:
 Limited Accessibility: Variables declared within a function are not accessible from outside that function.
 Temporary Lifetime: Exists only during the function execution and are destroyed once the function terminates.
 Memory Efficiency: Local variables manage memory efficiently because they are created and destroyed as needed.
9
Web Developer-Python
Global, Local variables
Example - Local scope
Consider the following example where x is a local variable:
10
Web Developer-Python
Global, Local variables
Example - Local scope
In this example
 x is defined inside the local_scope_example function.
 x can only be accessed within the local_scope_example function.
 Trying to access x outside the function will result in a NameError.
11
Web Developer-Python
Global, Local variables
Importance of local scope
 Encapsulation: Local scope helps in encapsulating the logic and data within a function, promoting modularity and
reducing the likelihood of unintended interference between different parts of a program.
 Debugging and Maintenance: Code with well-defined local scopes is easier to debug and maintain because the
behavior of variables is predictable and confined to specific regions.
 Memory Management: Local variables are automatically managed and cleaned up by Python’s memory
management system, which helps in efficient use of memory.
12
Web Developer-Python
Global, Local variables
Global scope
 Global scope refers to the area of a Python program that is outside of all functions and classes.
 Variables defined in this scope are called global variables. These variables can be accessed from any part of the
program, including inside functions and classes, unless shadowed by a local variable.
13
Web Developer-Python
Global, Local variables
Global scope
Characteristics of global scope:
 Accessibility: Global variables are accessible throughout the entire module in which they are declared.
 Lifetime: Global variables exist for the duration of the program's execution.
 Namespace: Global variables reside in the global namespace, which is created when the program starts and is
maintained until the program terminates.
14
Web Developer-Python
Global, Local variables
Example - Global scope
Consider the following example where x is a local variable within the function local_scope_example:
15
Web Developer-Python
Global, Local variables
Example - Global scope
In this example:
 x is defined outside of any function, making it a global variable.
 example_function can access and print x because it is in the global scope.
16
Web Developer-Python
Global, Local variables
The “global” keyword
 To modify a global variable inside a function, the global keyword must be used.
 It tells Python that the variable is global and should not be treated as a local variable within the function.
17
Web Developer-Python
Global, Local variables
Example - “global” keyword
In this example:
 y is defined in the global scope.
 The modify_global_variable function uses the
global keyword to modify y.
 Both the function and the global scope see the
updated value of y.
18
Web Developer-Python
Global, Local variables
Avoiding conflicts with global variables
If a local variable within a function has the same name as a global variable, the local variable will shadow the global
variable within that function. This means that the global variable remains unchanged, and the local variable is used
within the function.
19
Web Developer-Python
Global, Local variables
Example - Avoiding conflicts with global variables
In this example:
 z is defined in the global scope.
 shadowing_example defines a local
variable z that shadows the global
variable z.
 The global variable z remains unchanged
outside the function.
20
Web Developer-Python
Global, Local variables
Importance of global scope
 Data Sharing: Global variables allow data to be shared across different parts of the program.
 Configuration Constants: Global scope is often used for defining configuration constants and settings that need to
be accessed throughout the program.
 Modular Design: In a modular design, global scope helps in defining variables that need to be accessed by
multiple modules.
21
Web Developer-Python
2. Nonlocal Variable
22
Web Developer-Python
Nonlocal variable
Enclosing scope
 It refers to the scope of any enclosing (or outer) functions.
 This is particularly relevant when dealing with nested functions, where a function is defined inside another function.
 The enclosing scope allows the inner function to access variables from the outer function.
23
Web Developer-Python
Nonlocal variable
Enclosing scope
Characteristics of enclosing scope
 Accessibility: Variables defined in the enclosing scope can be accessed by inner functions.
 Nonlocal Variables: The nonlocal keyword can be used to modify variables in the enclosing scope from within the
inner function.
 Intermediate Scope: Enclosing scope acts as an intermediate scope between the local and global scopes.
24
Web Developer-Python
Nonlocal variable
Example - Enclosing scope
In this example:
 “a” is defined in outer_function, making it part of the
enclosing scope for inner_function.
 inner_function can access and print a because it is
within its enclosing scope.
25
Web Developer-Python
Nonlocal variable
The “nonlocal” keyword
 The nonlocal keyword is used in nested functions to modify a variable in the enclosing (outer) function scope.
 It provides a way to access and change variables from the enclosing scope that are neither global nor local to the
inner function.
26
Web Developer-Python
Nonlocal variable
The “nonlocal” keyword
Characteristics of the “nonlocal” Keyword
 Enclosing Scope: It allows access to variables in the nearest enclosing scope, which is not the global scope.
 Nested Functions: Useful primarily in the context of nested functions.
 Intermediate Scope: Provides a mechanism to work with intermediate scopes between local and global.
27
Web Developer-Python
Nonlocal variable
Example - “nonlocal” keyword
In this example:
 x is defined in outer_function, making
it part of the enclosing scope for
inner_function.
 inner_function uses the nonlocal
keyword to modify x.
 The value of x is changed to 20 both
within inner_function and when
accessed again in outer_function.
28
Web Developer-Python
Nonlocal variable
Example - “nonlocal” keyword
In this example:
 x is defined in outer_function, making it part of the enclosing scope for inner_function.
 inner_function uses the nonlocal keyword to modify x.
 The value of x is changed to 20 both within inner_function and when accessed again in outer_function.
29
Web Developer-Python
Nonlocal variable
Nested functions and multiple levels of enclosing scope
 The nonlocal keyword applies to the nearest enclosing scope.
 If there are multiple nested levels, it affects the nearest enclosing variable.
30
Web Developer-Python
Nonlocal variable
Example - Nested functions and multiple levels of enclosing scope
In this example:
 “a” is defined in first_level and redefined
in second_level.
 third_level can access and modify “a”
from second_level using the nonlocal
keyword.
 The nonlocal keyword does not affect the
a defined in first_level because it only
applies to the nearest enclosing scope.
31
Web Developer-Python
Nonlocal variable
Example - Nested functions and multiple levels of enclosing scope
In this example:
 “a” is defined in first_level and redefined
in second_level.
 third_level can access and modify “a”
from second_level using the nonlocal
keyword.
 The nonlocal keyword does not affect the
a defined in first_level because it only
applies to the nearest enclosing scope.
32
Web Developer-Python
Nonlocal variable
Common Use Cases
 Stateful Closures: Maintaining state across function calls within closures.
 Callbacks: Modifying shared state in callback functions.
 Encapsulation: Encapsulating logic and state within a function and its nested functions.
33
Web Developer-Python
Nonlocal variable
Differences between “global” and “nonlocal”
 Scope:
• global affects variables in the global scope.
• nonlocal affects variables in the nearest enclosing scope that is not global.
 Usage Context:
• global is used for modifying global variables.
• nonlocal is used within nested functions to modify variables in the enclosing scope.
34
Web Developer-Python
3. Global Keyword and Namespaces
35
Web Developer-Python
Global scope and modules
 In larger Python programs, global variables are often defined in a module.
 When you import the module, you can access its global variables.
Global Keyword and Namespaces
36
Web Developer-Python
Example - Global scope and modules
In this example:
 “a” is a global variable in “module1.py”.
 “main.py” imports “module1” and accesses and modifies “a”.
Filename - main.py
Global Keyword and Namespaces
Filename – module1.py
37
Web Developer-Python
Namespaces
A namespace in Python is a mapping between names and objects. Different namespaces exist for different scopes,
and they ensure that names are unique and won't lead to naming conflicts.
Types of Namespaces
 Built-in Namespace: Contains built-in functions and exceptions (e.g., print(), len()). Created when the Python
interpreter starts.
 Global Namespace: Contains names defined at the module level. Each module has its own global namespace.
 Enclosing Namespace: Contains names in any enclosing function (when using nested functions).
 Local Namespace: Contains names defined inside a function. Created when the function is called and deleted
when the function returns.
Global Keyword and Namespaces
38
Web Developer-Python
Example - Namespaces
Global Keyword and Namespaces
39
Web Developer-Python
Differences between scope and namespace
 Scope:
• Defines the region where a variable is accessible.
• Determines the lifetime and visibility of a variable.
 Namespace:
• A mapping from names to objects.
• Ensures that names are unique within their context.
Global Keyword and Namespaces
40
Web Developer-Python
Case Study: Questions on scope and namespace
Scenario 1: Working with list
Background
A company needs a function to manage employee names in a list. The list should be updated from both within the main function and
nested functions.
Question
Define a global list employee_names. Create a function manage_employees that adds a new employee name to the list. Within
manage_employees, create another function promote_employee that removes an employee from the list and adds them to a
promotion list, which is local to manage_employees. Ensure that the updates to employee_names are reflected globally.
Python Scope
41
Web Developer-Python
Case Study: Questions on scope and namespace
Scenario 2: Working with tuple.
Background
A program needs to handle configuration settings stored in a tuple. These settings need to be accessed in nested functions without
modifying them.
Question
 Define a global tuple config_settings with some configuration values. Create a function read_config that prints the settings.
Within read_config, create another function inner_read that prints a specific setting. Demonstrate how to access the global
config_settings from both functions.
 Discuss why tuples are appropriate for storing configuration settings in this scenario.
Python Scope
42
Web Developer-Python
Case Study: Questions on scope and namespace
Scenario 3: Working with dictionary.
Background
A library system manages books with a dictionary where keys are book IDs and values are book titles. Nested functions need to
update this dictionary.
Question
 Define a global dictionary books. Create a function manage_books that adds a new book to the dictionary. Within
manage_books, create another function remove_book that removes a book by its ID. Ensure that changes to books are reflected
globally.
 Describe how the books dictionary is updated globally and why dictionaries are suitable for this use case.
Python Scope
43
Web Developer-Python
Case Study: Questions on scope and namespace
Scenario 4: Working with set.
Background
An application tracks unique user IDs in a set. The set should be modified within a function that processes user logins.
Question
 Define a global set user_ids. Create a function process_login that adds a new user ID to the set. Demonstrate how the global
user_ids set is updated from within the function.
 Explain how using a set ensures the uniqueness of user IDs and why the global keyword is necessary in this case.
Python Scope
44
Web Developer-Python
Case Study: Questions on scope and namespace
Scenario 5: Working with string.
Background
A text processing application manages a global string containing a paragraph. The application needs to count words and replace
certain words within nested functions.
Question
 Define a global string paragraph. Create a function process_text that counts the number of words in the paragraph. Within
process_text, create another function replace_word that replaces a specific word. Demonstrate how to modify and access the
global paragraph string within these functions.
 Explain why strings are immutable and how the global keyword allows modifications to the paragraph string.
Python Scope
45
Web Developer-Python
Question?
46
Web Developer-Python
Thank you
47

More Related Content

PPTX
LOCAL VARIABLES AND GLOBAL VARIABLES.pptx
PPTX
Chapter-3 Scoping.pptx
PPTX
scopeofvariables in pyuthon using va.pptx
PPTX
Scope of Variables.pptx
PPTX
scope of python
PDF
Important JavaScript Concepts Every Developer Must Know
LOCAL VARIABLES AND GLOBAL VARIABLES.pptx
Chapter-3 Scoping.pptx
scopeofvariables in pyuthon using va.pptx
Scope of Variables.pptx
scope of python
Important JavaScript Concepts Every Developer Must Know

Similar to 1.3 - Python ScopePPtforpythonlearners.pptx (20)

DOC
Basic construction of c
PPT
Android coding guide lines
PDF
What is Closure and Its Uses in PHP
PPTX
Scope rules : local and global variables
PDF
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
PPT
Object Oriented Concepts and Principles
PPTX
FUNCTIONS.pptx
PDF
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
PDF
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
DOCX
Chapter 5: Names, Bindings and Scopes (review Questions and Problem Set)
PDF
Python Environment Variables A Step-by-Step Tutorial for Beginners
PDF
🐍⚡ “Python Panache: Code Like a Pro, Not a Programmer!”
PDF
379008-rc217-functionalprogramming
PDF
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
PDF
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
PDF
Top 80 Interview Questions on Python for Data Science | Tutort - Best Data Sc...
PDF
Python Namespace.pdf
PDF
Password protected diary
PDF
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
Basic construction of c
Android coding guide lines
What is Closure and Its Uses in PHP
Scope rules : local and global variables
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
Object Oriented Concepts and Principles
FUNCTIONS.pptx
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
Chapter 5: Names, Bindings and Scopes (review Questions and Problem Set)
Python Environment Variables A Step-by-Step Tutorial for Beginners
🐍⚡ “Python Panache: Code Like a Pro, Not a Programmer!”
379008-rc217-functionalprogramming
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
Top 80 Interview Questions on Python for Data Science | Tutort - Best Data Sc...
Python Namespace.pdf
Password protected diary
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
Ad

More from IstarthaPD (7)

PPTX
Monika PPT of the technical presentation
PPTX
Rahul.pt of technical seminar and internship
PPTX
TECHNICAL SEMINAR presentation for 8th sem
PPTX
Technical Seminar presentation topic for 8th sem
PPTX
Annual-Day-Cultural-Program-Plan (1).pptx
PPTX
BiryaniCommunication for the academic requirements
PPTX
1.2 - Tuplesforthepythonlearnersino.pptx
Monika PPT of the technical presentation
Rahul.pt of technical seminar and internship
TECHNICAL SEMINAR presentation for 8th sem
Technical Seminar presentation topic for 8th sem
Annual-Day-Cultural-Program-Plan (1).pptx
BiryaniCommunication for the academic requirements
1.2 - Tuplesforthepythonlearnersino.pptx
Ad

Recently uploaded (20)

PPTX
_Dispute Resolution_July 2022.pptxmhhghhhh
PPTX
microtomy kkk. presenting to cryst in gl
PPTX
PE3-WEEK-3sdsadsadasdadadwadwdsdddddd.pptx
PPT
APPROACH TO DEVELOPMENTALlllllllllllllllll
PPTX
DPT-MAY24.pptx for review and ucploading
PDF
Why Today’s Brands Need ORM & SEO Specialists More Than Ever.pdf
PPTX
Overview Planner of Soft Skills in a single ppt
PPTX
1751884730-Visual Basic -Unitj CS B.pptx
PPT
notes_Lecture2 23l3j2 dfjl dfdlkj d 2.ppt
PPTX
Autonomic_Nervous_SystemM_Drugs_PPT.pptx
PPTX
Cerebral_Palsy_Detailed_Presentation.pptx
PPTX
Sports and Dance -lesson 3 powerpoint presentation
PPTX
OnePlus 13R – ⚡ All-Rounder King Performance: Snapdragon 8 Gen 3 – same as iQ...
PPT
Gsisgdkddkvdgjsjdvdbdbdbdghjkhgcvvkkfcxxfg
PDF
Manager Resume for R, CL & Applying Online.pdf
PPTX
Nervous_System_Drugs_PPT.pptxXXXXXXXXXXXXXXXXX
PPTX
FINAL PPT.pptx cfyufuyfuyuy8ioyoiuvy ituyc utdfm v
PDF
313302 DBMS UNIT 1 PPT for diploma Computer Eng Unit 2
PPT
BCH3201 (Enzymes and biocatalysis)-JEB (1).ppt
PDF
L-0018048598visual cloud book for PCa-pdf.pdf
_Dispute Resolution_July 2022.pptxmhhghhhh
microtomy kkk. presenting to cryst in gl
PE3-WEEK-3sdsadsadasdadadwadwdsdddddd.pptx
APPROACH TO DEVELOPMENTALlllllllllllllllll
DPT-MAY24.pptx for review and ucploading
Why Today’s Brands Need ORM & SEO Specialists More Than Ever.pdf
Overview Planner of Soft Skills in a single ppt
1751884730-Visual Basic -Unitj CS B.pptx
notes_Lecture2 23l3j2 dfjl dfdlkj d 2.ppt
Autonomic_Nervous_SystemM_Drugs_PPT.pptx
Cerebral_Palsy_Detailed_Presentation.pptx
Sports and Dance -lesson 3 powerpoint presentation
OnePlus 13R – ⚡ All-Rounder King Performance: Snapdragon 8 Gen 3 – same as iQ...
Gsisgdkddkvdgjsjdvdbdbdbdghjkhgcvvkkfcxxfg
Manager Resume for R, CL & Applying Online.pdf
Nervous_System_Drugs_PPT.pptxXXXXXXXXXXXXXXXXX
FINAL PPT.pptx cfyufuyfuyuy8ioyoiuvy ituyc utdfm v
313302 DBMS UNIT 1 PPT for diploma Computer Eng Unit 2
BCH3201 (Enzymes and biocatalysis)-JEB (1).ppt
L-0018048598visual cloud book for PCa-pdf.pdf

1.3 - Python ScopePPtforpythonlearners.pptx

  • 2. Web Developer-Python Error/ Warning Information Flashback Class Exercise 2
  • 3. Web Developer-Python AGENDA 1. Global, local variables 2. Nonlocal variable 3. Global keywords and namespaces 3
  • 5. Web Developer-Python Global, Local variables Scope  In Python, scope refers to the region or context in a program where a variable or a function is accessible.  It defines the visibility and lifetime of a variable.  Python uses a system of nested scopes, where each level has access to variables defined in its own scope and those in its parent scopes, but not in its child scopes. 5
  • 6. Web Developer-Python Global, Local variables The LEGB Rule  Local(L), Enclosing(E), Global(G) and Built-in(B).  The LEGB rule in Python is a hierarchy that the interpreter follows to resolve the names of variables.  It stands for Local, Enclosing, Global, and Built-in.  This rule helps Python determine the scope of a variable and which value to use when there are multiple definitions of the same name in different scopes. 6
  • 7. Web Developer-Python Global, Local variables Types of scope 1. Local scope 2. Global scope 3. Enclosing scope 4. Built-in scope 7
  • 8. Web Developer-Python Global, Local variables Local scope  Local scope refers to the region within a function where the variables and names defined are accessible.  Variables created inside a function are said to be in the local scope of that function.  These variables are only available within the function where they are created and cannot be accessed outside of it. 8
  • 9. Web Developer-Python Global, Local variables Local scope Characteristics of local scope:  Limited Accessibility: Variables declared within a function are not accessible from outside that function.  Temporary Lifetime: Exists only during the function execution and are destroyed once the function terminates.  Memory Efficiency: Local variables manage memory efficiently because they are created and destroyed as needed. 9
  • 10. Web Developer-Python Global, Local variables Example - Local scope Consider the following example where x is a local variable: 10
  • 11. Web Developer-Python Global, Local variables Example - Local scope In this example  x is defined inside the local_scope_example function.  x can only be accessed within the local_scope_example function.  Trying to access x outside the function will result in a NameError. 11
  • 12. Web Developer-Python Global, Local variables Importance of local scope  Encapsulation: Local scope helps in encapsulating the logic and data within a function, promoting modularity and reducing the likelihood of unintended interference between different parts of a program.  Debugging and Maintenance: Code with well-defined local scopes is easier to debug and maintain because the behavior of variables is predictable and confined to specific regions.  Memory Management: Local variables are automatically managed and cleaned up by Python’s memory management system, which helps in efficient use of memory. 12
  • 13. Web Developer-Python Global, Local variables Global scope  Global scope refers to the area of a Python program that is outside of all functions and classes.  Variables defined in this scope are called global variables. These variables can be accessed from any part of the program, including inside functions and classes, unless shadowed by a local variable. 13
  • 14. Web Developer-Python Global, Local variables Global scope Characteristics of global scope:  Accessibility: Global variables are accessible throughout the entire module in which they are declared.  Lifetime: Global variables exist for the duration of the program's execution.  Namespace: Global variables reside in the global namespace, which is created when the program starts and is maintained until the program terminates. 14
  • 15. Web Developer-Python Global, Local variables Example - Global scope Consider the following example where x is a local variable within the function local_scope_example: 15
  • 16. Web Developer-Python Global, Local variables Example - Global scope In this example:  x is defined outside of any function, making it a global variable.  example_function can access and print x because it is in the global scope. 16
  • 17. Web Developer-Python Global, Local variables The “global” keyword  To modify a global variable inside a function, the global keyword must be used.  It tells Python that the variable is global and should not be treated as a local variable within the function. 17
  • 18. Web Developer-Python Global, Local variables Example - “global” keyword In this example:  y is defined in the global scope.  The modify_global_variable function uses the global keyword to modify y.  Both the function and the global scope see the updated value of y. 18
  • 19. Web Developer-Python Global, Local variables Avoiding conflicts with global variables If a local variable within a function has the same name as a global variable, the local variable will shadow the global variable within that function. This means that the global variable remains unchanged, and the local variable is used within the function. 19
  • 20. Web Developer-Python Global, Local variables Example - Avoiding conflicts with global variables In this example:  z is defined in the global scope.  shadowing_example defines a local variable z that shadows the global variable z.  The global variable z remains unchanged outside the function. 20
  • 21. Web Developer-Python Global, Local variables Importance of global scope  Data Sharing: Global variables allow data to be shared across different parts of the program.  Configuration Constants: Global scope is often used for defining configuration constants and settings that need to be accessed throughout the program.  Modular Design: In a modular design, global scope helps in defining variables that need to be accessed by multiple modules. 21
  • 23. Web Developer-Python Nonlocal variable Enclosing scope  It refers to the scope of any enclosing (or outer) functions.  This is particularly relevant when dealing with nested functions, where a function is defined inside another function.  The enclosing scope allows the inner function to access variables from the outer function. 23
  • 24. Web Developer-Python Nonlocal variable Enclosing scope Characteristics of enclosing scope  Accessibility: Variables defined in the enclosing scope can be accessed by inner functions.  Nonlocal Variables: The nonlocal keyword can be used to modify variables in the enclosing scope from within the inner function.  Intermediate Scope: Enclosing scope acts as an intermediate scope between the local and global scopes. 24
  • 25. Web Developer-Python Nonlocal variable Example - Enclosing scope In this example:  “a” is defined in outer_function, making it part of the enclosing scope for inner_function.  inner_function can access and print a because it is within its enclosing scope. 25
  • 26. Web Developer-Python Nonlocal variable The “nonlocal” keyword  The nonlocal keyword is used in nested functions to modify a variable in the enclosing (outer) function scope.  It provides a way to access and change variables from the enclosing scope that are neither global nor local to the inner function. 26
  • 27. Web Developer-Python Nonlocal variable The “nonlocal” keyword Characteristics of the “nonlocal” Keyword  Enclosing Scope: It allows access to variables in the nearest enclosing scope, which is not the global scope.  Nested Functions: Useful primarily in the context of nested functions.  Intermediate Scope: Provides a mechanism to work with intermediate scopes between local and global. 27
  • 28. Web Developer-Python Nonlocal variable Example - “nonlocal” keyword In this example:  x is defined in outer_function, making it part of the enclosing scope for inner_function.  inner_function uses the nonlocal keyword to modify x.  The value of x is changed to 20 both within inner_function and when accessed again in outer_function. 28
  • 29. Web Developer-Python Nonlocal variable Example - “nonlocal” keyword In this example:  x is defined in outer_function, making it part of the enclosing scope for inner_function.  inner_function uses the nonlocal keyword to modify x.  The value of x is changed to 20 both within inner_function and when accessed again in outer_function. 29
  • 30. Web Developer-Python Nonlocal variable Nested functions and multiple levels of enclosing scope  The nonlocal keyword applies to the nearest enclosing scope.  If there are multiple nested levels, it affects the nearest enclosing variable. 30
  • 31. Web Developer-Python Nonlocal variable Example - Nested functions and multiple levels of enclosing scope In this example:  “a” is defined in first_level and redefined in second_level.  third_level can access and modify “a” from second_level using the nonlocal keyword.  The nonlocal keyword does not affect the a defined in first_level because it only applies to the nearest enclosing scope. 31
  • 32. Web Developer-Python Nonlocal variable Example - Nested functions and multiple levels of enclosing scope In this example:  “a” is defined in first_level and redefined in second_level.  third_level can access and modify “a” from second_level using the nonlocal keyword.  The nonlocal keyword does not affect the a defined in first_level because it only applies to the nearest enclosing scope. 32
  • 33. Web Developer-Python Nonlocal variable Common Use Cases  Stateful Closures: Maintaining state across function calls within closures.  Callbacks: Modifying shared state in callback functions.  Encapsulation: Encapsulating logic and state within a function and its nested functions. 33
  • 34. Web Developer-Python Nonlocal variable Differences between “global” and “nonlocal”  Scope: • global affects variables in the global scope. • nonlocal affects variables in the nearest enclosing scope that is not global.  Usage Context: • global is used for modifying global variables. • nonlocal is used within nested functions to modify variables in the enclosing scope. 34
  • 35. Web Developer-Python 3. Global Keyword and Namespaces 35
  • 36. Web Developer-Python Global scope and modules  In larger Python programs, global variables are often defined in a module.  When you import the module, you can access its global variables. Global Keyword and Namespaces 36
  • 37. Web Developer-Python Example - Global scope and modules In this example:  “a” is a global variable in “module1.py”.  “main.py” imports “module1” and accesses and modifies “a”. Filename - main.py Global Keyword and Namespaces Filename – module1.py 37
  • 38. Web Developer-Python Namespaces A namespace in Python is a mapping between names and objects. Different namespaces exist for different scopes, and they ensure that names are unique and won't lead to naming conflicts. Types of Namespaces  Built-in Namespace: Contains built-in functions and exceptions (e.g., print(), len()). Created when the Python interpreter starts.  Global Namespace: Contains names defined at the module level. Each module has its own global namespace.  Enclosing Namespace: Contains names in any enclosing function (when using nested functions).  Local Namespace: Contains names defined inside a function. Created when the function is called and deleted when the function returns. Global Keyword and Namespaces 38
  • 39. Web Developer-Python Example - Namespaces Global Keyword and Namespaces 39
  • 40. Web Developer-Python Differences between scope and namespace  Scope: • Defines the region where a variable is accessible. • Determines the lifetime and visibility of a variable.  Namespace: • A mapping from names to objects. • Ensures that names are unique within their context. Global Keyword and Namespaces 40
  • 41. Web Developer-Python Case Study: Questions on scope and namespace Scenario 1: Working with list Background A company needs a function to manage employee names in a list. The list should be updated from both within the main function and nested functions. Question Define a global list employee_names. Create a function manage_employees that adds a new employee name to the list. Within manage_employees, create another function promote_employee that removes an employee from the list and adds them to a promotion list, which is local to manage_employees. Ensure that the updates to employee_names are reflected globally. Python Scope 41
  • 42. Web Developer-Python Case Study: Questions on scope and namespace Scenario 2: Working with tuple. Background A program needs to handle configuration settings stored in a tuple. These settings need to be accessed in nested functions without modifying them. Question  Define a global tuple config_settings with some configuration values. Create a function read_config that prints the settings. Within read_config, create another function inner_read that prints a specific setting. Demonstrate how to access the global config_settings from both functions.  Discuss why tuples are appropriate for storing configuration settings in this scenario. Python Scope 42
  • 43. Web Developer-Python Case Study: Questions on scope and namespace Scenario 3: Working with dictionary. Background A library system manages books with a dictionary where keys are book IDs and values are book titles. Nested functions need to update this dictionary. Question  Define a global dictionary books. Create a function manage_books that adds a new book to the dictionary. Within manage_books, create another function remove_book that removes a book by its ID. Ensure that changes to books are reflected globally.  Describe how the books dictionary is updated globally and why dictionaries are suitable for this use case. Python Scope 43
  • 44. Web Developer-Python Case Study: Questions on scope and namespace Scenario 4: Working with set. Background An application tracks unique user IDs in a set. The set should be modified within a function that processes user logins. Question  Define a global set user_ids. Create a function process_login that adds a new user ID to the set. Demonstrate how the global user_ids set is updated from within the function.  Explain how using a set ensures the uniqueness of user IDs and why the global keyword is necessary in this case. Python Scope 44
  • 45. Web Developer-Python Case Study: Questions on scope and namespace Scenario 5: Working with string. Background A text processing application manages a global string containing a paragraph. The application needs to count words and replace certain words within nested functions. Question  Define a global string paragraph. Create a function process_text that counts the number of words in the paragraph. Within process_text, create another function replace_word that replaces a specific word. Demonstrate how to modify and access the global paragraph string within these functions.  Explain why strings are immutable and how the global keyword allows modifications to the paragraph string. Python Scope 45