0

I am new to Python and I am trying to make a game that includes a 2D array as a board. I looked for how to declare a 2D array from StackOverflow previously but for some reason I get a NameError that cols is not defined. What am I am doing wrong?

class HelloWorld:
    rows = 5
    cols = 5
    arr = [[0 for i in range(cols)] for j in range(rows)]

Edit: This is the traceback:

Traceback (most recent call last):
  File "c:/Users/MyName/Documents/Python Scripts/HelloWorld.py", line 1, in <module>
    class HelloWorld:
  File "c:/Users/MyName/Documents/Python Scripts/HelloWorld.py", line 4, in HelloWorld
    arr = [[0 for i in range(cols)] for j in range(rows)]
  File "c:/Users/MyName/Documents/Python Scripts/HelloWorld.py", line 4, in <listcomp>
    arr = [[0 for i in range(cols)] for j in range(rows)]
NameError: name 'cols' is not defined
colidyre
  • 4,170
  • 12
  • 37
  • 53
Anonymous
  • 93
  • 8
  • can we see the exact error trace? – ab123 Aug 22 '19 at 04:23
  • 1
    Note that variables declared at the scope of a class are class variables, not instance variables. They are shared between all instances, meaning you could not have instances with different game boards. – MisterMiyagi Aug 22 '19 at 06:55
  • 1
    Possible duplicate of [Accessing class variables from a list comprehension in the class definition](https://stackoverflow.com/questions/13905741/accessing-class-variables-from-a-list-comprehension-in-the-class-definition) – MisterMiyagi Aug 22 '19 at 06:58

0 Answers0