Joey Jordan
Joey Jordan

Reputation: 37

Getting an error with my for loop involving numpy arrays

I'm making a game and I'm getting the error: "IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices."

In the following block of code, play_game is a function that returns a string, and roll_dice is a random array. Basically, I'm trying to get all the strings into an array, so into total_games. However, I can't do this because of this error, which I'm not sure exactly what it means. If someone could clarify what the error means or how I can fix this code it'd be greatly appreciated.

def game_session(num_games=50):
    total_games = np.zeros(num_games)
    for i in total_games:
        total_games[i] = play_game(roll_dice())
    return total_games

Upvotes: 0

Views: 75

Answers (2)

Szymon Maszke
Szymon Maszke

Reputation: 24691

You cannot input string into np.array of type np.float64, as this data structure contains only one type (by default np.float64 as in this example).

What you are after is a normal Python's list, try this code:

def game_session(num_games=50):
    total_games = []
    for _ in range(num_games):
        total_games.append(play_game(roll_dice()))
    return total_games

@Loocid's answer is also right, there are multiple problems with your code.

Actually you can (and probably should) do it more pythonic like this:

def game_session(num_games=50):
    return [play_game(roll_dice()) for _ in range(num_games)]

Upvotes: 1

Loocid
Loocid

Reputation: 6441

.zeros creates an array of floating point zeros (0.0).

When you do for i in total_games, i will always be 0.0 and obviously total_games[0.0] can't be done for the reason your error message suggets.

I belive what you want is for i in range(len(total_games)) which will iterate through the indicies of total_games, ie 0, 1, 2, 3, ....

Upvotes: 1

Related Questions