Python Tutorial @ Home

# Python Scope Of Variable 3

Local and Global Variables

```def myfun():
a=15 //local variable
print(a)
a=95   // global variable
print(a)
myfun()
print(a)```

Output:

95
15
95
>>>

In the above program variable a is declared in local as well as global scope. But the value of a in both the region is different . The variable ‘a’ in myfun() is local to this function but outside this function variable a is a global variable.

Example 2:

```def calsum(x,y):
z=x+y
return(z)
num1=int(input(‘enter first no.: ‘))
num2=int(input(‘enter sec. no.: ‘))
s=calsum(num1,num2)
Print(‘sum of given nos = ‘,s)```

Output:
enter first no.: 10
enter sec. no.: 20
sum of given nos = 30
>>>

In the above program three variables-num1, num2 and s are global variables while x, y, z which are declared inside the function are local variables( local to the function calsum().

Example 3:

```#function definition
def calsum(x,y,z):
s=x+y+z
return(s)

def average(a,b,c):
s1=calsum(a,b,c)
return(s1/3)

#function calling
num1=int(input('enter first no.: '))
num2=int(input('enter sec. no.: '))
num3=int(input('enter third no.: '))
av= average(num1,num2,num3)
print('Average of given nos = ',av)```

Output:
enter first no.: 50
enter sec. no.: 60
enter third no.: 10
Average of given nos = 40.0
>>>

In the above program we can see –
Local environment of calsum() function where x,y,z and s are its local variables.
Local environment of average() function where a, b, c and s1 are its local variables.
Global environment where num1, num2, num3 and av are global variables.

Example 4:

```def calsum(x,y):
z=x+y
print(num1, num2)
return(z)
num1=int(input(‘enter first no.: ‘))
num2=int(input(‘enter sec. no.: ‘))
s=calsum(num1,num2)
print(‘sum of given nos = ‘,s)```

Output:
enter first no.: 10
enter sec. no.: 20
10 20
sum of given nos = 30
>>>

In this program num1 and num2 variables can be accessed from inside the function since they are global variables

Important Pages