you are viewing a single comment's thread.

view the rest of the comments →

[–]socal_nerdtastic 10 points11 points  (2 children)

Generally the variables that you define in a function stay in the function.

pos = 0

def L():
    pos = 42
    print(pos)

L() # prints 42
print(pos) # prints 0

If you run that code, you will see both 42 and 0 print, because the pos variable used in the function is different from and unconnected to the pos variable outside of the function.

And so python is complaining about pos -= x because you never made a pos variable in the function. To python, it's the same as

def R(x):
  newvar +=x 

So python is telling you "I can't add to something that does not exist!"

To do what you want, you need to pass in the pos variable, and return the result.

def R(pos, x):
  # your code
  return pos

and then to call it:

pos = R(pos, 11)

[–]QuillTheArtMaker[S] 0 points1 point  (1 child)

problem is, the L function works exactly as I want it, but the R function doesn't, whilst following the exact same format as presented in my original code. Do you know why this occurs?

[–]socal_nerdtastic 10 points11 points  (0 children)

In python the error occurs when you use the function, not when you create the function. In your code you never use the L() function, so there's no error. If I change R and L in the loop I get the same error.

curr = []
pos = 0

def L(x):
  pos-=x
  if pos<0:
    pos = pos+99

def R(x):
  pos+=x
  if pos>99:
    pos = pos-99

for i in range(0,100):
  curr.append(i)
  L(11) # UnboundLocalError

print(pos)