0

While learning python, I have an understanding that python runs Line by line and unless a line of code is not executed it does not create or assign variable and all was fine with this theory, until I tried something like:

X = 1

def method1():
    print (X)  # Why global X, is not printed here
    X = 20
    print (X)  # and then use local X here

I know global keyword can solve it also if I remove the assignment of X inside method1() would solve it and global X gets printed, but I am not able to understand how python knows before hand that I have a var assignment of same name somewhere down the code in function?

Any help would be appriciated.

Vivek
  • 175
  • 1
  • 9
  • The answer is at https://stackoverflow.com/questions/423379/using-global-variables-in-a-function#423596 – Paula Thomas Jul 21 '18 at 10:21
  • Python scans your code before running it, as showing in the example below. That's why if you make an indentation error, it knows (e.g., having an `if` statement with no body). – Neel Kamath Jul 21 '18 at 10:23

1 Answers1

1

The scope cannot be mixed within a code block.

https://docs.python.org/3.6/reference/executionmodel.html#resolution-of-names

(emphasis mine)

If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block. This can lead to errors when a name is used within a block before it is bound. This rule is subtle. Python lacks declarations and allows name binding operations to occur anywhere within a code block. The local variables of a code block can be determined by scanning the entire text of the block for name binding operations.

Mike Scotty
  • 10,530
  • 5
  • 38
  • 50