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.

2
  • The answer is at stackoverflow.com/questions/423379/… Commented Jul 21, 2018 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). Commented Jul 21, 2018 at 10:23

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.