Python – How to Create a Random Range but Exclude a Specific Number

if-statementpythonrandomrangewhile-loop

I have the following code:

while True:
    if var_p1 != "0":
        break
    else:
        import random
        var_p1 = random.randint(-5,5)

I want the loop to repeat until var_p1 equals anything but zero. However, I get zero all the time. What am I doing wrong?

Best Answer

Answering the question in the title, not the real problem (which was answered by Daniel Roseman):

How do you create a random range, but exclude a specific number?

Using random.choice:

import random
allowed_values = list(range(-5, 5+1))
allowed_values.remove(0)

# can be anything in {-5, ..., 5} \ {0}:
random_value = random.choice(allowed_values)  
Related Question