I know that this error message has been discussed already a lot but I haven't found an explanation of the following:
def random2(seed):
x = seed
def update():
x = ( x * 16807 ) % 2147483647
return x
return update
r = random2(17283945)
print(r())
This doesn't work because the scope of the variable x seems to get lost by returning the function [UnboundLocalError]. Ok. But now I've found out that there is absolutely no problem with
def random(seed):
x = [seed]
def update():
x.append(( x.pop() * 16807 ) % 2147483647 )
return x[0]
return update
r = random(17283945)
print(r()) #580971270
print(r()) #1923475628
print(r()) #1783541505
I'm a little confused why, in this case, the scope of x remains valid. It seems that is has something to do with (im)mutability, but this still doesn't make a lot of sense to me.
Thanks a lot.