0

test.py

x = 10;   # global variable

def func1():
  print(x);  # prints 10

def func2()
  x = x + 1;  # IDE shows error: "Unresolved reference of x(RHS of expression)

def func3()
  global x;
  x = x + 1;  # This works

When x has a global scope, why doesn't func2() allow me to modify its value though it is accessible as seen in func1(). And why does it require explicit mention of "global" keyword as in case of func3() ?

Harish Harry
  • 45
  • 1
  • 7

1 Answers1

1

You can access global variables but for modifying them it should be explicitly declared that variable is a global variable.

I think this link would be useful.

The reason behind it is that when you say x = x + 1, python thinks that you want a local variable x and then when reaches the x + 1 expression python finds out that the local variable x was mentioned but not assigned any value so it gets confused.

Farbod Shahinfar
  • 777
  • 6
  • 15