-->

Global Variables Can Be Read from a Local Scope [Python]

 Consider the following program:

  1. def spam():
  2. print(eggs)
  3. eggs = 42
  4. spam()
  5. print(eggs)

Since there is no parameter named eggs or any code that assigns eggs a value in the spam() function, when eggs is used in spam(), Python considers it a reference to the global variable eggs. This is why 42 is printed when the previous program is run.



Local and Global Variables with the Same Name To simplify your life, avoid using local variables that have the same name as a global variable or another local variable. But technically, it’s perfectly legal to do so in Python. To see what happens, type the following code into the file editor and save it as sameName.py:


  1. def spam():
  2. eggs = 'spam local'
  3. print(eggs) # prints 'spam local'
  4. def bacon():
  5. eggs = 'bacon local'
  6. print(eggs) # prints 'bacon local'
  7. spam()
  8. print(eggs) # prints 'bacon local'
  9. eggs = 'global'
  10. bacon()
  11. print(eggs) # prints 'global'

When you run this program, it outputs the following:
bacon local
spam local
bacon local
global

There are actually three different variables in this program, but confusingly they are all named eggs. The variables are as follows:

  1. A variable named eggs that exists in a local scope when spam() is called.
  2. A variable named eggs that exists in a local scope when bacon() is called.
  3. A variable named eggs that exists in the global scope.

Since these three separate variables all have the same name, it can be confusing to keep track of which one is being used at any given time. This is why you should avoid using the same variable name in different scopes.


Baca Juga


Related Posts

0 Response to "Global Variables Can Be Read from a Local Scope [Python]"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel