Sample bartleby Q&A Solution
You ask questions, our tutors answer
Browse
Question

What are the different variable scopes in python?

Expert Answer

A variable assigned inside a function is of local scope and is visible only inside the function as demonstrated by the list variable a. Any attempt to print the variable outside the scope of the function my_func results into an error as shown in the code snippet. This happens because no variable with name a has been assigned (defined) with global scope at the python console:

Here we define (assign) a variable a with global scope at the python console, however when we call the earlier defined function my_func we get the same output as earlier as the function re-defines the variable a with local scope and prints it. When we again try to print the variable a from the python console (global scope) we are able to see the contents of variable a defined with global scope.

In function my_func2 we try to modify and print the variable a defined in global scope (this function has not re-defined the variable a within its scope). Two subsequent calls to the same function results in accumulation of the result in the global scoped variable a across the calls as demonstrated below:

In the code snippet we demonstrate how to define a variable with global scope inside a function. Here the variable a is no more local scoped as earlier and is visible outside the function scope as demonstrated by the print call to the variable a directly from the python console (global scope):