Problem with random and if statement

I have this script:

    regCOLOR = random.uniform(1, 5)
    own["prop"] = regCOLOR
    
    if regCOLOR == 1: 
        regalCOLOR = ('A')
    if regCOLOR == 2: 
        regalCOLOR = ('B')
    if regCOLOR == 3: 
        regalCOLOR = ('C')
    if regCOLOR == 4: 
        regalCOLOR = ('D')
    if regCOLOR == 5: 
        regalCOLOR = ('E')

The random number works but the if statement doesn’t do anything and doesn’t show any problem. It just won’t set anything to regalCOLOR.
Did I write something wrong and that’s why it doesn’t work?

What are you hoping will happen by setting that variable?

As far as I can see, you’re simply setting a variable and then doing nothing with it.

That one is only to test if the random variable works.
The if that should set regalCOLOR doesn’t work.

image

That function returns a float, which doesn’t match any of your ‘if’ statements. You could int() it for a hacky fix, but it’ll never equal 5 so you’ll want to increase the range to 1,6.

oh my bad, I see that’s the problem. I guess it should be random.randit.

indeed

    own = cont.owner
    
    regCOLOR = random.randint(1,5)
    own["prop"] = regCOLOR
    
    if regCOLOR == 1: 
        regalCOLOR = ('A')
    elif regCOLOR == 2: 
        regalCOLOR = ('B')
    elif regCOLOR == 3: 
        regalCOLOR = ('C')
    elif regCOLOR == 4: 
        regalCOLOR = ('D')
    elif regCOLOR == 5: 
        regalCOLOR = ('E')
    
    print(regalCOLOR)

If you just use 1 of the outcome then an elif is better and faster.

2 Likes

this particular example can be cooked down to this.

rc = ['', 'A', 'B', 'C', 'D', 'E']
own["prop"] = random.randint(1, 5)
regalCOLOR = rc[own["prop"]]

print(regalCOLOR)

no if or elif needed, the output from the randint is predictable (range from 1 to 5) so a simple lookup would do just fine.

3 Likes

i completely agree, but if you use a list then i would simply use random.choice

    rc = ['A', 'B', 'C', 'D', 'E']
    regalCOLOR = random.choice(rc)

    print(regalCOLOR)

But it all depends on what the TS wants/ need it for.

3 Likes

I didn’t even know you could do it like this. Thank you.

1 Like

@edderkop @Cotaks Your solutions are both beautiful, thanks for sharing them : D

2 Likes