Functions - local variable and different use cases

what’s the difference b/w them all?

and what’s a local variable?

Hi @dikshant9sharma

  • Global Variables : In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function.
  • Local Variables : A variable declared inside the function’s body or in the local scope is known as a local variable.
  • Nonlocal Variable : nonlocal keyword is used to make the variable which refers to the variable bounded in the nearest scope. Scope to which variable it bound should not be global or local scope.

In the given examples:

  1. In outer() function x (x=10) have a local scope (i.e calling x outside the function would cause an error), there is a nested inner() function. We use nonlocal keywords to create a nonlocal variable. Thus any change made to variable x would directly affect the x defined in outer function. The inner() function is defined in the scope of another function outer() .

  2. In outer1() function x is having a local scope, there is a nested inner() function over where we created a new variable x which have a scope only limited to inner() function only and have nothing to do with the variable x defined in outer() function. Thus any change made to variable x defined in inner() function won’t affect variable x of outer() function.

Hope this might helps :slight_smile:

now the question arise why does the value of x did not update from 10 to 15 in outer () and why is outer1() having no output.

Hi @dikshant9sharma

Reason why x did not update from 10 to 15 in outer () is because you haven’t called the inner () . And in outer1() didn’t have any print statement , all the print statement are being called inside inner() function and as you haven’t called the inner () function thus no print statement is being executed
inner () is function is being called inside itself {recursion}.
You can refer to the following code —>

Hope this might helps :slight_smile:

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.