Showing posts with label Python keyword. Show all posts
Showing posts with label Python keyword. Show all posts

Tuesday, February 2, 2021

Nonlocal Keyword in Python With Examples

In this post we’ll see what is nonlocal keyword in Python and how to use it.

To understand nonlocal keyword better an understanding of local, global and nonlocal variables is required, as a requisite please go through this post- Local, Nonlocal And Global Variables in Python

Python nonlocal keyword

The nonlocal keyword causes the variable to refer to previously bound variables in the nearest enclosing scope excluding globals. Note that nonlocal keyword is added in Python 3.

Python nonlocal keyword is used with variables in nested functions to bind the variable defined in outer function, by making variable nonlocal it can be accessed in nested function.

Let’s try to understand it with some examples.

Global Keyword in Python With Examples

In this post we’ll see what is global keyword in Python and how to use it.

To understand global keyword better an understanding of local, global and nonlocal variables is required, as a requisite please go through this post- Local, Nonlocal And Global Variables in Python

Some important points that you should know about local and global variables in Python-

  1. Variables that are declared outside a function are known as global variables in Python. There is no need to qualify these variables with global keyword such variables have global scope by default.
  2. When a variable is declared inside a function then it is a local variable. A local variable’s scope is limited with in the function where it is created.
  3. If you declare a variable inside a function having the same name as the global variable then with in the scope of the method local variable overshadows the global variable.