Good day to all. I am trying to build a game called 2048.I made a variable named box and added 4 lists each list containing a 4 empty values to be replaced later.Then I declared it global(tried reverse too:declared global and then made the values inside them).when I call global box in one function(to do changes to the box),it works.then I called another function which changes position of box and it too passed without a error.but the third where I assign the box to another variable with list comphrehension like this:
box = [[[]]*4 for i in range(4)] # this is box
box1 = [box[i][::-1] for i in range(4)] # tried to do this
the second function didn't require box1 but I called it to see if any error occurs.Nothing occurs. but when I do same with the next function error "NameError:free variable box referenced before assignment in enclosing scope" occurs.
why is that.what did I do wrong? here is the code
import random
global box
box = [[[]]*4 for i in range(4)]
def adding():
digit = random.choice([2,4])
empty = [index for index,i in enumerate(box[0]) if i==[]]
add = random.choice(empty)
try:
for i in range(3):
if box[i][add] == [] and box[i+1][add] != []:
box[i][add] = digit
break
elif box[-1][add] == []:
box[-1][add] = digit
break
except:
print('Error Occured')
def right():
box1=[box[i][::-1] for i in range(4)]
for i in range(4):
take = box[i]
box[i]=[[] for x in take if x ==[]]
for j in [x for x in take if x != []]:
box[i].append(j)
def left():
box1 = [box[i][::-1] for i in range(4)]
right()
box1 = [box[i][::-1] for i in range(4)]
box= box1
error occurs at function left()
tried in different os too.
thanks.works when I declared global inside function but ca anyone explain why did it work for right() but not for left()?
You must declare it global inside the function, not outside. Module level variables are always global:
box = ...
def left():
global box # unnecessary, if not assigned a value
box1 = [box[i][::-1] for i in range(4)]
def foo():
global box # necessary, otherwise box is local
box = bar
The global declaration is unnecessary, as you are only using the variable and not assigning it a new value. It i therefore considered global by default. See the docs:
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With