user3896917
user3896917

Reputation:

TypeError: tuple indices must be integers, not tuple

I am making a dice simulator, and I was testing the aesthetics when I encountered this error:

Traceback (most recent call last):
  File "C:/Users/Jacob/Documents/Code/Test.py", line 22, in <module>
    for j in DiceSides[i]:
TypeError: tuple indices must be integers, not tuple

Here is my code:

Segments = {
0: '\t.-------.',
1: '\t|       |',
2: '\t|   O   |',
3: '\t|     O |',
4: '\t| O     |',
5: '\t| O   O |',
6: '\t| O O O |',
7: "\t'-------'"
}

DiceSides = (
(0, 1, 2, 1, 7),
(0, 3, 1, 4, 7),
(0, 4, 2, 3, 7),
(0, 5, 1, 5, 7),
(0, 5, 2, 5, 7),
(0, 6, 1, 6, 7)
)

for i in DiceSides:
    for j in DiceSides[i]:
        print(Segments[j])

I don't understand this TypeError, could someone explain to me what the problem is?

Upvotes: 2

Views: 1674

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125058

You are looping over the elements of DiceSides:

for i in DiceSides:

i is not an index here, it is bound to the tuples of DiceSides. The for statement in Python is really a Foreach loop, you get the actual elements from the iterable, rather than indexes into the iterable.

As such, because i is already a tuple, you can just loop over the value directly:

for i in DiceSides:
    for j in i:
        print(Segments[j])

An alternative spelling would be:

for i in DiceSides:
    print(*(Segments[seg] for seg in i), sep='\n')

Demo:

>>> for i in DiceSides:
...     print(*(Segments[seg] for seg in i), sep='\n')
... 
    .-------.
    |       |
    |   O   |
    |       |
    '-------'
    .-------.
    |     O |
    |       |
    | O     |
    '-------'
    .-------.
    | O     |
    |   O   |
    |     O |
    '-------'
    .-------.
    | O   O |
    |       |
    | O   O |
    '-------'
    .-------.
    | O   O |
    |   O   |
    | O   O |
    '-------'
    .-------.
    | O O O |
    |       |
    | O O O |
    '-------'

Upvotes: 1

Related Questions