Learning Python - 6th day (Noon)

 Watched this video: Click here


I have learnt about global and local variables in this tutorial.

I know that I have functions in Python. And I also know what they can do. 

But I have a question, can I create new variables in a function? Yes I can!

Example:

| def myFunction():
|    a = 10
|    print(a)  

Output: 10

Okay, it works then! But the variable 'a' is created within the function myFunction() , right?
What if the variable 'a' is already defined outside the function myFunction() ? Will it change the value of previous variable?

Answer is No! Any new variable that is created within the function, or any variable which is used inside the function is the local variable of that function. No other code outside that function can use them. 

For example:

1| def myFunction():
2|    a = 10
3|    print(a)  
4|
5| print(a)  

Output: #Error: 'a' is not defined in line 5

Here we can call 'a' is a local variable for myFunction()

What if we define a outside the function myFunction(). Will it affect the code inside the function?

No! Variable outside the function is called global variables. We can use them only outside the function. New variable should be created in a function to use a global variable's value.

For example: 

a = 10
def myFunction():
a=15
print('In function "a" is: ',a)

myFunction()
print('Outside function "a" is: ',a)

Output: 

In function "a" is:  15
Outside function "a" is:  10

Okay okay now I know about global and local variable. But another question. How can I use a global variable in a function? How can I fetch the value of it?

For this you need to create a local variable first and by using an array call globals(), we can fetch the value of a global variable.

Example: 

a = 10
def myFunction():
x=globals()['a']
print('In function value is: ',x)

myFunction()
print('Outside function value is: ',a)

Output:

In function value is:  10
Outside function value is:  10

Simply the function is globals()['variableName']


Comments

Popular posts from this blog

Husband's Affair with Step Daughter Ends in Grisly Murder (True Crime Documentary)