The focus of this part is an area of problems where scoping in Python is misunderstood. Usually, when we have global variables (okay, I’ll say it because I have to - global variables are bad), Python understands it if we access them within a function:
This is a companion discussion topic for the original entry at http://amir.rachum.com/blog/2013/07/09/python-common-newbie-mistakes-part-2/
Thanks for the nice series, I keep learning from it! The example:
bar = 
>>> print bar
however is wrong (actually it's correct but doesn't make sense), as the foo() part is missing.
Open your eyes man ... foo() is used in the next code snippet!!
It appears completely incorrect to me.
bar = 
You open your eyes man, lol
"The first misconception is that Python, being an interpreted language
(which is awesome, I think we can all agree), is executed line-by-line.
In truth, Python is being executed statement-by-statement. "
Dude, what are you smoking?
When I try the following code:
bar = 
print(bar) >> prints ""
test() >> executes test() code
print(bar) >> prints "[42, 1]"
The same example in your code seems to have different results...is this a mistake?
It's correct, but it doesn't do a single thing with foo(). Yes, the best way would be print bar, foo(), print bar
Your blog seems to be blocked in Facebook. You might want to check that out.
I have to admit I made a mistake, and your comment was valid ... The third code snippet should call 'foo()' then call 'print(bar)' ... And it turns out that bar is modified to [42, 0] (test on both Python-2 and 3).
In what way is it blocked? I shared it without any problems.
I understand the problem with this explanation, but it's the best novice-friendly way I could come up with to explain my point.
bar = 
def foo(): bar.append(0)
Is still wrong. It should print [42, 0]
The last code segment has wrong indentation.
The "def foo(): ..." block should be indented.
The first misconception is that python is an interpreted language. Python is a compiled language just like Java. Even when you run a code in the "interpreter", this code is actually compiled to byte code and the byte code is then executed in a virtual machine!