3

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()?

2
  • No point in declaring global outside a function and fix your indentation Commented Jan 20, 2017 at 9:24
  • use global box inside your function Commented Jan 20, 2017 at 9:24

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

2

global is used inside the function, not out side.

So at the top of your file you can do

box = []

and inside your function:

global box
# now change box the way you want

Comments

Your Answer

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.