Search code examples
pythonlistcolors

Trying to randomly choose and reassign one of three variables in python


New to python. I tried to assign three variables in a function, then try to reassign one of them at random to a different value, then be able to use all three later.

I tried to create a list containing the three variables, then make an outlier variable that is assigned to one of the three at random and then reassigned to a new value. However, the values it is returning are still all between 200 and 255.

import random

def newcolor():
  global logocolor, rvalue, gvalue, bvalue
  rvalue = random.randint(200, 255)
  gvalue = random.randint(200, 255)
  bvalue = random.randint(200, 255)
  colorvalues = [rvalue, gvalue, bvalue]
  outliercolor = random.choice(colorvalues)
  outliercolor = random.randint(0, 55)
  logocolor = (int(rvalue), int(gvalue), int(bvalue))

newcolor()

Solution

  • Looks like you are confused about variable names and values in python. I suggest you read through this very useful post: https://nedbatchelder.com/text/names.html

    You seem to have the misconception that random.choice(colorvalues) will choose one of the variable names you put in the list, and then assigning to that variable name will modify the original value. The list doesn't know about any of the variable names. It only knows about the values assigned to those variables.

    Instead, you should pick a random index of the list to modify, and then modify that index.

    You're also misusing global variables. You should instead return the values you want from your function, and assign them where you call the function.

    def newcolor():
        rvalue = random.randint(200, 255)
        gvalue = random.randint(200, 255)
        bvalue = random.randint(200, 255)
    
        outliercolor = random.randint(0, 55)
    
        colorvalues = [rvalue, gvalue, bvalue]
    
        random_index = random.randint(0, 2)
        colorvalues[random_index] = outliercolor
    
        return tuple(colorvalues)
    
    logocolor = newcolor()
    

    Of course, this code can be reduced by creating the list directly instead of assigning color values to variables and then putting those into the list:

    def newcolor():
        colorvalues = [random.randint(200, 255), random.randint(200, 255), random.randint(200, 255)]
        random_index = random.randint(0, 2)
        colorvalues[random_index] = random.randint(0, 55)
        return tuple(colorvalues)
    

    Alternatively, you could simply create a list with two colors and one outlier color, and use random.shuffle to shuffle the list around:

    def newcolor():
        colorvalues = [random.randint(200, 255), random.randint(200, 255), random.randint(0, 55)]
        random.shuffle(colorvalues)
        return tuple(colorvalues)