Python scopes

The Python nonlocal Keyword

The Python nonlocal keyword is used to access and modify variables from an outer (but not global) scope in nested functions (i.e. non-local variables). It tells Python that a variable assigned in a nested function should refer to a variable in the nearest enclosing scope that is not global. Otherwise, Python will create a new variable in the local scope of the nested function.

The Python global Keyword

The global keyword in Python is used to access and modify global variables from within a function's local scope. It tells Python that a variable assigned in a function should refer to a global variable. Otherwise, Python will create a local variable of the same name.

Understanding Python Scopes

A scope is the extent of visibility and accessibility of named entities such as variables, functions, and classes, within a program. It determines where in your code you can access a particular name or identifier. There are three types of Python scopes: build-in, global, and local.