Python scope

A variable is only available from inside the block of code where it is created. The block is called the scope of the variable.

Local Scope

  • variable can be accessed inside the block of the code
  • if variable created inside function then it can be accessed inside the function only
def square_of_num(num):
    npow = 2
    return 
print(square_of_num(10))
# output: 100
  • variable npow can be accessed inside function only otherwise it will throw NameError
  • variable npow is called as local variable

Function Inside Function

  • the local variable can be accessed from a function within the function.
  • lets look at the below code

def func():
  x = 300
  def inner():
    return x
  return inner()

output = func()
print(output)
# output: 300
* when the code is executed it returns the value of the variable x

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.
x = 100

def func():
  print(x)

func()
# output: 100
print(x)
# output: 100

Naming Variables

  • same variable name can be used in both local and global scopes.
  • gobal scope varible can't be overridden by the local variable.
name = "Anji"

def change_name():
    name = "Avtar"
    print(name)

change_name()
# output: "Avtar"
print(name)
# output: "Anji"

Global Keyword

  • global variable value can be udated inside the function by using the global keyword
name = "Anji"

def change_name():
    global name
    name = "Avtar"
    print(name)

change_name()
# output: "Avtar"
print(name)
# output: "Avtar"