Search code examples
pythonarraysglobal-variables

Assign a global Array in Python


I found a project to learn Python: Tetris My plan was to assign a global Array in a variable() function to clean up my main() function.

but i get a syntax error

def globalv():
    global x
    x = 40
    global y
    y = 10
    global Tetris[40][10]
    for x in 40:
        for y in 10:
            Tetris[x][y] = 0

def main():
    globalv()

if __name__ == "__main__":
    main()

I don't know what i'm doing wrong Thank you


Solution

  • Your error is in the for loops as well as the use of global Tetris[40][10].

    The error on global is simply that you have added the index, you only make global the variable itself. So:

    global Tetris

    If you are more familiar with C or Java, the fact that you need to declare variables and their sizes is not a thing in python (at the most basic levels).

    The error you are getting on the for loops should be something along the lines of: TypeError: 'int' object is not iterable

    The for keyword requires an iterator, this is essentially something you go through in steps, like a list. Integers are not iterable, the "literal" english of saying "for number in 40" makes sense but it does not in code.

    What you need is to use the range keyword which will generate essentially a list of numbers up to, but not including, the number. So you should use:

    for x in range(40):