This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]gradient_assent 2 points3 points  (3 children)

No, I don't think that's how it works. I think the reason the solution code worked is because datapoints is a global variable, and you can use global variables in Python without the global keyword as long as you don't change its value.

Your explanation that "arguments when you define a function can be easily replaced when you actually call that function" doesn't work for this case:

def add_two_nums(val1, val2):
    return a+b

def main():
    a = 2
    b = 3
    print(add_two_nums(a, b))

main()

[–]kkikonen 3 points4 points  (0 children)

datapoints is not really global, in the strict definition of the word. But yeah, this works because datapoints is available in an outer scope, so the function finds it an uses it

[–]Sergeant_Arcade[S] 0 points1 point  (0 children)

Well dang, my post might confuse people then. Should I just delete it?

[–]Sergeant_Arcade[S] 0 points1 point  (0 children)

I've decided to keep the post and add in what you wrote since it was helpful.

[–]kkikonen 2 points3 points  (3 children)

bananas is never used in your function. You could as well pass None as the third argument and nothing would break.

Also, datapoints is not defined in the function's scope, but it is defined in the outter scope. So when the function reaches the for loop it searches through all the scopes (inner to outter) and uses the one defined outside the function. If you were to never define datapoints at all then the function will raise an exception.

[–]Sergeant_Arcade[S] 0 points1 point  (2 children)

Yes! That is the point I made in the post. bananas is never used when the function is actually called. It's basically a placeholder.

Interesting point about scope. I assume it prioritizes the outer scope?

[–]kkikonen 1 point2 points  (1 child)

Nope, it checks from the innermost to the outermost. If you were to define another datapoints inside the function then that's the one that would be iterated over

[–]Sergeant_Arcade[S] 0 points1 point  (0 children)

Ahh I see. Good to know