0

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

2 Answers 2

1

.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, ....

Sign up to request clarification or add additional context in comments.

5 Comments

Doing that fixes it, but now I get an error: could not convert string to float. This is because play_game() returns a string
In that case, the answer @Szymon Maszke provided may be more what you need.
Ok yea. Only problem with that one is it has to be the size of the parameter num_games and I can't iterate through an empty list.
@JoeyJordan is that what you are after?
@SzymonMaszke yea sorry I should've clarified. I need it to be the size of num_games
1

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)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.