user1212818
user1212818

Reputation:

Python For/If Syntax Error

Here's my code:

for i in tuples:
    if i[0] == "U_shape":
        pieces.append(U_shape(i[1], boardLength, i[2])
    if i[0] == "I_shape":
        pieces.append(I_shape(i[1], i[2])
    if i[0] == "L_shape":
        pieces.append(L_shape(i[1], boardLength, i[2])
    if i[0] == "T_shape":
        pieces.append(T_shape(i[1], boardLength, i[2])
    if i[0] == "X_shape":
        pieces.append(X_shape(i[1], boardLength, i[2])

Here's the Error:

if i[0] == "I_shape":
                    ^
SyntaxError: invalid syntax

Upvotes: 0

Views: 207

Answers (4)

pepr
pepr

Reputation: 20794

Another straightforward improvement is:

for i in tuples:
    if i[0] == "U_shape":
        pieces.append(U_shape(i[1], boardLength, i[2]))
    elif i[0] == "I_shape":
        pieces.append(I_shape(i[1], i[2]))
    elif i[0] == "L_shape":
        pieces.append(L_shape(i[1], boardLength, i[2]))
    elif i[0] == "T_shape":
        pieces.append(T_shape(i[1], boardLength, i[2]))
    elif i[0] == "X_shape":
        pieces.append(X_shape(i[1], boardLength, i[2]))

I guess that Hugh Bothwell's will be the fastest, but...

>>> import this
The Zen of Python, by Tim Peters
...
In the face of ambiguity, refuse the temptation to guess.
...
>>>

and measure using the timeit module.

Upvotes: 1

Thomas
Thomas

Reputation: 3693

You're missing closing parentheses on every line that calls pieces.append.

Upvotes: 9

Hugh Bothwell
Hugh Bothwell

Reputation: 56694

pieceType = {
    "U_shape": U_shape,
    "I_shape": I_shape,
    "L_shape": L_shape,
    "T_shape": T_shape,
    "X_shape": X_shape
}

pieces = [pieceType[a](b, boardLength, c) for a,b,c in tuples]

Upvotes: 5

Gareth Latty
Gareth Latty

Reputation: 89097

As others have said, you are missing closing brackets, but that has been said, there is more needed to be done on your code structure:

This is a really bad way of doing what you want to do. A much better solution is to use a dict:

mapping = {"U_shape": U_shape, "I_shape": I_shape, ...}
pieces.append(mapping[i[0]](i[1], boardLength, i[2]))

Now, this does rely on all your classes taking the same arguments - and while they don't appear to, this (given the errors already in your code) could be a mistake. If it's not, you could separate out that case, and use the mapping for the other cases.

Upvotes: 1

Related Questions