Because you're defining a new variable called number
inside the function.
Here's what your code effectively does:
def test():
if regex.match("hello"):
number = number + 1
When Python first compiles this function, as soon as it sees number =
, that makes number
into a local. Any reference to number
inside that function, no matter where it appears, will refer to the new local. The global is shadowed. So when the function actually executes and you try to compute number + 1
, Python consults the local number
, which hasn't been assigned a value yet.
This is all due to Python's lack of variable declaration: because you don't declare locals explicitly, they're all declared implicitly at the top of the function.
In this case, you can use global number
(on its own line) to tell Python you always want to refer to the global number
. But it's often better to avoid needing this in the first place. You want to combine some kind of behavior with some kind of state, and that's exactly what objects are for, so you could just write a small class and only instantiate it once.