0

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    You need to declare them in any function that tries to assign a value to one. It's not needed to just reference the current value of one. Putting it outside any function like you have done doesn't do anything (except perhaps to explicitly document how the variable is going to be used). – martineau Apr 28 '18 at 10:48

2 Answers2

1

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.

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
1

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

Mehdi
  • 1,260
  • 2
  • 16
  • 36