0

I am learning Python with Automate the Boring Stuff with Python. In chapter 3 it talks about functions and scopes etc. It states that a local scope can use global scopes. However, with the example code below, it is not true?

Example Code:

def spam():
    print(eggs) #Error!
    eggs = 'spam local'

eggs = 'global'
spam()

I understand logically that because eggs has not been assigned a value before we are executing print and it is exactly what the book says. But my question is since, eggs has been assigned a value in the global scope. Why does Python not revert to the global scope to pull variable. Since again, local can call/pull global but not other local, but global can't pull local.

Cheers.

Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
  • 1
    FWIW, if you get rid of the line `eggs = 'spam local'`, it will print global. – Mateen Ulhaq May 07 '21 at 01:31
  • 1
    Lesson: pass parameters to your function instead of relying on global variables. – Code-Apprentice May 07 '21 at 01:34
  • If you're really interested about the technical details, [read here](https://docs.python.org/3/reference/executionmodel.html#resolution-of-names)... but realistically, I only use non-constant global variables 0.01% of the time, so this isn't really an issue in practice. – Mateen Ulhaq May 07 '21 at 01:38

1 Answers1

1

Look at this code here.

eggs = 'global'
def spam():
    print(eggs) #No Error!
spam()

It does not give us an error. But say we preformed something on eggs.

eggs = 'global'
def spam():
    print(eggs) 
    eggs += " and bacon"#Error!
spam()

We are going to get an error.UnboundLocalError: local variable 'eggs' referenced before assignment. This is most likely why we have the option to pass variables through functions as arguments.

eggs = 'global'
def spam(eggs):
    print(eggs) 
    eggs += " and bacon"
    return eggs
print(spam(eggs))

output

global
global and bacon

Does any of this make sense?

Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
  • Sorry mate, it does not the First section or part does upto "This is most likely why we have the option to pass variables through functions as arguments." and I get all that. I even read the link to my question which may be similar. Idk if I wrote my questions wrong or something else, but I will just re-write it here. My question is if we assigned a value to a local state and the local states can call global scopes. Why does the above mentioned code, through an error? Should it not just call the global variable assigned to eggs? Which is 'global'? – LearningTheRopes May 10 '21 at 04:46
  • Your question was closed because it is similar to this. https://stackoverflow.com/questions/370357/unboundlocalerror-on-local-variable-when-reassigned-after-first-use. Does that help? – Buddy Bob May 10 '21 at 04:51