I am working on a python thing and I assigned variable x*y to SecureNum. I then define a function in which I write: while R*S != SecureNum: it spits up the error that I am referencing SecureNum before assignment, even though it has been assignment earlier but not in the function. How can I fix this?
Thanks in advance! George
2 Answers 2
Probably you are trying to assign to SecureNum later in that function
Because you haven't declared SecureNum to be global and Python sees you are assigning to it, it forces it to be a local variable.
SecureNum = 12345
def f(R, S):
if R * S != SecureNum: #<== local SecureNum shadows the global one
...
...
SecureNum = ... #<= This means SecureNum is a local
def g(R, S):
global SecureNum
if R * S != SecureNum: #<== now this is the global SecureNum
...
...
SecureNum = ... #<= and so is this one
This can be surprising because the problem isn't because really at the line where you are testing the value, it's because you are trying to rebind the name further down.
Comments
Use the following at the beginning of your function:
global SecureNum
SecureNumas an argument, or to put theSecureNumvariable and your function together in a class, etc. There are a lot of reasons to avoid avoid global variables.