SoFunction
Updated on 2024-11-16

Python Beginner's Tutorial (XXV) Python's Scope

Variables are only available within the created area. This is called a scope.

local scope

Variables created inside a function belong to the local scope of that function and can only be used inside that function.

an actual example

Variables created inside a function are available inside that function:

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

myfunc()

running example

100

Functions inside functions

As shown in the above example, the variable x is not available outside the function, but it is available to any function inside the function:

an actual example

Ability to access local variables from a function within a function:

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

myfunc()

running example

100

global scope

Variables created in the body of Python code are global variables and are globally scoped.

Global variables are available in any scope (global and local).

an actual example

Variables created outside of a function are global variables and can be used by anyone:

x = 100

def myfunc():
  print(x)

myfunc()

print(x)

running example

100
100

named variable

If you manipulate variables with the same name inside and outside a function, Python treats them as two separate variables, one available globally (outside the function) and one available locally (inside the function):

an actual example

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

x = 100

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

myfunc()

print(x)

running example

200
100

Global Keywords

If you need to create a global variable that is stuck in local scope, you can use the global keyword.

The global keyword makes the variable global.

an actual example

If the global keyword is used, the variable is globally scoped:

def myfunc():
  global x
  x = 100

myfunc()

print(x)

running example

100

Also, use the global keyword if you want to change global variables inside a function.

an actual example

To change the value of a global variable from within a function, reference the variable with the global keyword:

x = 100

def myfunc():
  global x
  x = 200

myfunc()

print(x)

running example

200

To this point this tutorial on Python Getting Started (XXV) Python scopes of the article is introduced to this, more related Python scopes of the content please search my previous posts or continue to browse the following related articles I hope that you will support me in the future more!