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 ...
This blog contains AI knowledge, algorithm, and python features for AI practitioners.