Skip to main content

Posts

Showing posts with the label Python keywords

Python 'global' and 'nonlocal' Keywords Explained with Examples

In Python, the keywords global and nonlocal are used when dealing with variable scope . In other words, they help determine where a variable is located when you access or modify it. 1. Scope Refresher Before we jump in, remember that  scope  refers to the part of a program where a variable is accessible. Local scope : Inside a function Global scope : Outside all functions Enclosing scope : A function inside another function Here's a visual diagram to help you understand variable scopes: 2.The  global  Keyword The global keyword is used to  modify a variable outside of the current function , specifically the one in the global scope. Normally, assigning to a variable inside a function creates a local variable. If you want to change a variable that exists at the global(module) level, you need to declare it global. Example 1: x = 10 def change_global () : global x x = 20 change_global() print(x) # Output: 20 Example 2: counter = 0 ...