Python Scope


Python Scope:


A variable is only available from inside the region it is created. This is called scope. Scope means availability of a variable around a limit.


Local Scope:


A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.

Example:

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

myfunc()

Output:
30


Global Scope:

A variable created in the main body of the Python code is a global variable and belongs to the global scope.
Global variables are available from within any scope, global and local.

Example:

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

myfunc()
print(x)

Output:
30
30

Note: The variable (x) is outside function which means that the variable (x) is having global scope and it can be use within as well as outside function.



Global Keyword:


The global keyword makes the variable global.

Example:

def myfunc():
  global x
  x = 30

myfunc()
print(x)

Output:
30


Post a Comment

0 Comments