Python Scope


Variables are only available within the built-in region. This is called width.


Local Scope

The variables created within the function are based on the local scope of that function, and can only be used within that function.


Example

A variable created inside a function is available inside that function:

def myfunc():
  x = 300
  print(x)

myfunc()

Function Inside Function

As described in the example above, variable x is not found outside the function, but is available in any function within the function:


Example

The local variable can be accessed from a function within the function:

def myfunc():
  x = 300
  def myinnerfunc():
    print(x)
  myinnerfunc()

myfunc()


Global Scope

The variables created by the Python coding body are global variables and are of global scope.

Global variables are available anywhere, global and local.


Example

A variable created outside of a function is global and can be used by anyone:

x = 300

def myfunc():
  print(x)

myfunc()

print(x)

Naming Variables

If you use the same dynamic word in and out of work, Python will treat them as two different variables, one available worldwide (outside of work) and one available locally (within-function):


Example

The function will print the local x, and then the code will print the global x:

x = 300

def myfunc():
  x = 200
  print(x)

myfunc()

print(x)


Global Keyword

If you need to create a global variable, but stick to a wide area, you can use a global keyword.

Global keyword makes dynamics more global.


Example

If you use the global keyword, the variable belongs to the global scope:

def myfunc():
  global x
  x = 300

myfunc()

print(x)

Also, use a global keyword if you want to make a change in the global variable within a function.


Example

To change the value of a global variable inside a function, refer to the variable by using the global keyword:

x = 300

def myfunc():
  global x
  x = 200

myfunc()

print(x)