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?
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
:"0" != 0
.You are comparing against a string, but
randint
gives you an integer.Well you check against a string to break the loop. So use:
instead of:
A memory efficient way to generate from
a
tob
but not including a valuec
is:This way, in the first step we'll generate a random int between
a
andc - 1
or betweenc
andb - 1
. In the second case we increment by one and we get a random number betweenc + 1
andb
. It's easy to see that each number betweena..(c - 1)
and(c + 1)..b
has the same probability.Your code fails because you're comparing an integer to a string. There are other problems with your code:
import
statement inside a loop.Here is a loop-free way to randomly generate a non-zero integer from -5 to +5, inclusive.
This code is guaranteed to call
random.randrange
exactly twice.As an alternative method, just pick one random element from the array, [-5, -4, -3, -2, -1, 1, 2, 3, 4, 5]. Guaranteed to work with just one call.