4

Here's my python 3 code. I would like to randomly select one of the cell variables (c1 through c9) and change its value to the be the same as the cpuletter variable.

import random

#Cell variables
c1 = "1"
c2 = "2"
c3 = "3"
c4 = "4"
c5 = "5"
c6 = "6"
c7 = "7"
c8 = "8"
c9 = "9"
cells = [c1, c2, c3, c4, c5, c6, c7, c8, c9]

cpuletter = "X"

random.choice(cells) = cpuletter

I'm getting a "Can't assign to function call" error on the "random.choice(cells)." I assume I'm just using it incorrectly? I know you can use the random choice for changing a variable like below:

import random
options = ["option1", "option2"]
choice = random.choice(options)

2 Answers 2

7

Problem:

random.choice(cells) returns a random value from your list, for example "3", and you are trying to assign something to it, like:

"3" = "X"

which is wrong.

Instead of this, you can modify the list, for example:

cells[5] = "X"

Solution:

You can use random.randrange().

import random
cells = [str(i) for i in range(1,10)] # your list
cpuletter = 'X'

print(cells)
random_index = random.randrange(len(cells)) # returns an integer between [0,9]
cells[random_index] = cpuletter
print(cells)

Output:

['1', '2', '3', '4', '5', '6', '7', '8', '9']
['1', '2', '3', '4', '5', '6', '7', 'X', '9']
-1

Random.choice(cells) returns a random element from cells, so if it returned element #0 and element #0 was the value "1", your original statement would essentially be saying "1" = "X" - obviously you can't assign the string literal to be something else, it's not a variable.

You'd instead want to get a random element #, and assign cells[rand_elt_num]. You could get the random element number by something simply like:

rand_elt_num = random.randint(0, len(cells)-1 )  #get index to a random element
cells[rand_elt_num] = "X"    # assign that random element

I think this is the same as what the other answer says, they just used random.randrange() instead.

1
  • Both values in random.randint() is inclusive. So, you need to do random.randint(0, len(cells)-1) instead of random.randint(0, len(cells)) if you really insist on using random.randint().
    – Sait
    Commented Aug 29, 2015 at 22:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.