Object Oriented Programming

Python Scope


Local Scope

The location where the programmer can find a variable and also access it is called the scope of a variable. Variable inside a function belongs to the local scope of that function, that variable can only be used inside that function.

Example

Local Scope Example

Output

300

NameError: name 'x' is not defined

Function Inside Function

Any function inside another function can access the outer function's variables.

Example

Function Inside Function Example

Output

300

Global Scope

Variables that are initialized in the main body of the Python code are global variables and belong to the global scope. Global variables are accessible in both global and local scopes.

Example

Global Scope Example

Output

300

300

If there are variables with the same name, one inside a function (local variable) and another outside the function (global variable), Python will consider these as two different variables.

Example

Global and Local Variable Example

Output

300

200

Global Keyword

If you need to create a global variable but are stuck in the local scope, you can use the global keyword. The global keyword makes the variable global.

Example

Global Keyword Example

Output

300