Python Scope

Scope changes the accessibility or visibility of classes, constructors, methods or variables.

Local Scope

A variable that is created inside a function has the local scope and it can be accessed only from within that function. Such variables are called local variables.

Example

def print_profile():
    #name and age variables have local scope here
    name = "Danny"
    age = 19
    print(name)
    print(age)
  

Global Scope

A variable which is created in the body of the python code and not inside the body of a function has the global scope. Such variables are accessible from anywhere in the code.

Example

#name and age variables have global scope here
name = "Danny"
age = 19

def print_profile():
    print(name)
    print(age)
  

Global Keyword

A variable with local scope can also be changed to global variable by using the global keyword.

Example

def print_profile():
    #name and age variables have global keyword
    global name = "Danny"
    global age = 19


print_profile()
print(name)
print(age)