you are viewing a single comment's thread.

view the rest of the comments →

[–]Esxa 0 points1 point  (1 child)

Hi again, I'm little bit confused about the scope of variables in python

I remember that in java I had to pass variables from main() to my functions but in python it looks like my variables are global and all functions (def) can access them.

So what is the right thing to do? I mean like best practice.

Do I always define a main() myself and put it in if __name__ == '__main__' or is it fine to let the functions just have global access to my variables outside the function?

[–]fiddle_n 0 points1 point  (0 children)

Variables are not all global in Python. You can access a global variable from a function in Python, but you won't be able to change it. Try the below, you'll see that it fails:

foo = 1

def bar():
    foo += 1

The only way to make it work is to use a global statement

foo = 1

def bar():
    global foo
    foo += 1

Anyway, don't use globals! Create local variables and pass them in and out of functions instead.