1.

Explain the scope of variables with an example?

Answer»

Scope of Variables:

Scope of variable refers to the part of the program, where it is accessible, i.e., area where you can refer (use) it. We can say that scope holds the current set of variables and their values. The two types of scopes are local scope and global scope.

(I) Local scope:

A variable declared inside the function’s body or in the local scope is called as local variable

Rules of local variable:

1. A variable with local scope can be accessed only within the function/block that it is created in.

2. When a variable is created inside the function/block; the variable becomes local to it.

3. A local variable only exists while the function is executing.

4. The formate arguments are also local to function.

Example:

Create a Local Variable

def loc ( ):

y = 0 # local scope

print (y)

loc ( )

Output:

0

(II) Global Scope:

A variable, with global scope can be used anywhere in the program. It can be created by defining a variable outside the scope of any function/block.

Rules of global Keyword:

The basic rules for global keyword in Python are:

1. When we define a variable outside a function, it’s global by default. You don’t have to useglobal keyword.

2. We use global keyword to read and write a global variable inside a function.

3. Use of global keyword outside a function has no effect

Example:

Global variable and Local variable with same name 

x = 5 def loc ( ):

x = 10

print (“local x:” , x)

loc ( )

print (“global x:” , x)

Output:

local x: 10

global x: 5

In above code, we used same name ‘x’ for both global variable and local variable. We get different result when we print same variable because the variable is declared in both scopes, i.e. the local scope inside the function loc() and global scope outside the function loc ( ).

The output:- local x: 10, is called local scope of variable.

The output: – global x: 5, is called global scope of variable.



Discussion

No Comment Found