0

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

asked Oct 22, 2013 at 0:33
1
  • You probably don't actually want to do this. It's better to pass SecureNum as an argument, or to put the SecureNum variable and your function together in a class, etc. There are a lot of reasons to avoid avoid global variables. Commented Oct 22, 2013 at 0:46

2 Answers 2

6

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.

answered Oct 22, 2013 at 0:37
Sign up to request clarification or add additional context in comments.

Comments

0

Use the following at the beginning of your function:

global SecureNum
answered Oct 22, 2013 at 0:36

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.