Question

I am working on a python project currently to create a game similar to pick up sticks, and I have come to a confusing point. I have created a list of lists, stickList, and I want to grab one of the values ([1, 2, 3]) and decrement a variable using it. Here is the code I am currently using:

If I have 30 sticksOnBoard I want the computer to grab 1, 2, or 3 sticks, decrement the sticks on the board by that number, and then have the loop pick up from there with the user. I'm not sure what I'm doing wrong though sadly, because the sticksOnBoard -= stickList(ballPick) isn't working.

Was it helpful?

Solution

If you want what I think you want, then what you want is the random module.

If you're using a list's length to determine your choices, you'll want to make sure that the choices are in range of the list. Fortunately using the range() feature does this automatically, so by getting the len() of the list before indexing, you'll never fail.

import random
my_choices = range(0, len(some_list))
print random.choice(my_choices)

EDIT: Ah, perhaps you're seeing the selection is out of range? Setting sticksOnBoard to the length of your list will cause an IndexError.

>>> mylist = [x for x in range(0, 16)] #this list will have items 0 through 15, for a total of 16
>>> mylist[16] #this is 1 too large for the list, however
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

If you always want the last item in the list, you can use mylist.pop() to always remove the last item in the list. If you're looping over a list, this could cause problems.

You can also index by using mylist[-1], which will always index the very last item in the list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top