What are the rules for a local and global variable in Python ?

  • In python local variables are those which are defined inside a function and its scope is limited to that function only whereas global variables are those which are not defined inside any function and have a global scope.
  • We can say that global variables are accessible throughout the program and inside every function whereas local variables are accessible only inside the function in which it was initialized.

Local Variables

  • Inside function local variables are those which are initialized and belongs only to that particular function.
  • Then it cannot be accessed anywhere outside the function.

Sample Code

[pastacode lang=”python” manual=”def%20f()%3A%0A%20%20%20%20%20%0A%20%20%20%20%23%20local%20variable%0A%20%20%20%20s%20%3D%20%22I%20love%20Wikitechy%22%0A%20%20%20%20print(s)%0A%20%0A%23%20Driver%20code%0Af()%0A” message=”” highlight=”” provider=”manual”/]

Output

Global Variables

  • Outside any function the global variables are those which are defined and which are accessible throughout the program.

Sample Code

[pastacode lang=”python” manual=”%23%20This%20function%20uses%20global%20variable%20s%0Adef%20f()%3A%0A%20%20%20%20print(%22Inside%20Function%22%2C%20s)%0A%20%0A%23%20Global%20scope%0As%20%3D%20%22I%20love%20Wikitechy%22%0Af()%0Aprint(%22Outside%20Function%22%2C%20s)%0A” message=”” highlight=”” provider=”manual”/]

Output

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like