VARIABLE SCOPE IN PYTHON

SAIROSHNI


Variable Scope

  • Variables are just containers for storing data values.
  • The location where we can find and access variables when required is called scope variable.
  • Variable scope is a determination of the lifetime of the variable.
  • Scope variables determines the accessibility and visibility of a variable.

There are four types of scope variable available in python:

  1. Local scope variable
  2. Enclosing scope variable
  3. Global scope variable
  4. Built-in scope variable

Local Scope Variable    

A variable created within a function can only be used within that function and is part of its local scope.

Program:


  def myfunction():
      myval=220
      print("Only within the declared functions can a local variable be accessed.",myval)
  print("Using a local variable outside of the function is impossible.")
  myfunction()


Output:


  Using a local variable outside of the function is impossible.
  Only within the declared functions can a local variable be accessed. 220


Enclosing Scope Variable

For the enclosed scope, we need to define an outer function enclosing the inner function. In the enclosed scope ,a variable defined and used in the outer function can not  be used directly in the inner function on the same name. If you define a same variable in inner function which is also exists in the outer function after the use of the variable, the python will generate error message.

Global Scope Variable

  • A global variable is one that is created in the main Python code and is part of the global scope.
  • Any global or local scope can be used to access global variables.

Program:


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


Output:


  200
  200


Built-In Scope Variable

The built-in scope is the widest scope in python. All the reserved names defined in python built-in modules have a built-in scope. When the python doesn't find an identifier in it's local, enclosing or global scope, it the looks in the built-in scope to see if it's defined there. If even it's not present in them it produces a error message.






More topic in Python

Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send