I want my method to have access to the variable defined outside the method, but even if i use global keyword it says it can't:
global var = 0
def test():
var = var +1
Compiler still says var is not defined in test method
Where is my mistake?
I want my method to have access to the variable defined outside the method, but even if i use global keyword it says it can't:
global var = 0
def test():
var = var +1
Compiler still says var is not defined in test method
Where is my mistake?
In Python you can't declare a variable global. You must declare your intent to change the variable in every function you want to use it in.
var = 0
def test():
global var
var += 1
But if it's not for a one-off 50 line script, at this point you should start to question whether it's such a good idea. Additionally, if you just need to read a variable from a higher scope, there's no need to declare it, it just works. Use global
only if you want to change the variable.
You have to declare global variable within function:
var = 0
def func():
global var
var += 1
Edit
Pay attention to comments: more generally within non-global scope