Scope and Lifetime of variables


Scope and Lifetime of variables

The scopes of the variables depend upon the particular location where the variable is being declared. Variables can be defined with the two types of scopes—
The place where we can locate a variable, and it is also accessible if needed, is named the scope of a variable. Every variable in a program is not possible to be accessed at every location in that program. It depends on how you have declared it in the program.
The scope of a variable defines the part of the program where you can enter an appropriate identifier.

There are two primary scopes of variables in Python:

  • Local variable
  • Global variable

Local variables:

The local variables are declared and defined inside the function and are only accessible inside it.

Global variables:

The global type of variables is the one that is determined and declared outside any of the functions and is not designated to any function. They are accessible in any part of the program by all the functions. Whenever you call a function, the declared variables inside it are carried into scope. The global variables are accessible from inside any scope, global and local.

The lifetime of a variable in Python:

The variable lifetime is the period during which the variable remains in the memory of the Python program. The variables' lifetime inside a function remains as long as the function runs. These local types of variables are terminated as soon as the function replaces or terminates.

Local variable

    example code

    def msg(): msg1="Hello world , this is a local variable " print(msg1) msg() print(msg1)

    OUTPUT

    Image Not Found

Global Variable

    example code

    def cal(args): s=0 for arg in args: s=s + arg print(s) s=0 args=[19,20,29] cal(args) print("outside the func.",s)

    OUTPUT

    Image Not Found