How is the Variable Available to the Function Without Being Passed as an Argument?


#1

how is the stock list available to the function without it being an argument to the function? Its scope should be local to main.


FAQ: Learn Python: A Day at the Supermarket - Stocking Out
#2

you mean stock dictionary?

stock is global. Its defined in the main body of the file, as such, its global.


#3

right, I meant dictionary (going to take me a while to use “list” and “dictionary” correctly instead of “array” and “hash”)

just did some reading on scope. the way python handles scope, it sure seems like it could lead to some difficult bug-hunting, especially if you screw up and redefine the variable inside a function.

And unless I misread, it looks like the only local variables are those defined inside functions. Is that correct?


#4

no, then local variable comes before global variable:

x = 3
def example():
    x = 5
    print x

example()

but yea, you have to be careful.

well, look at this example:


def outer_function():
    x = 5
    def inner_function():
        print x
    inner_function()

outer_function()

we can still access the x inside inner_function while x is defined in outer_function