DEV Community

Cover image for #Day1 - Nonlocal and Global Keywords in Python
Rahul Banerjee
Rahul Banerjee

Posted on • Originally published at realpythonproject.com

#Day1 - Nonlocal and Global Keywords in Python

Two keywords used to change the scope of a variable.

Nonlocal

Consider the above case where we have an inner function. We are trying to print a variable that was declared in the outer function, this will compile, and "Hello World" will be displayed. However, if we try to modify the variable str, we will get an error "Variable str references before assignment".

To avoid the error, we use the nonlocal keyword. The nonlocal keyword is used when we want to modify variables declared in the outer function.

The above code snippet would execute without any errors

Global

The global keyword is used when we want to modify a variable which was created outside the function.

In the above case, we are trying to modify the variable global_str which was created outside the function func

Example

  • We use the nonlocal keyword to modify the variable str inside func2
  • We use the global keyword to modify the variable global_str inside func2

Top comments (0)