Patrick Mlr - 28 days ago 5x
Python Question

# Python random while multiple conditions

Cheers, my problem is that I don't know how to do a while with multiple conditions. I really don't get it why this won't work:

``````import random

a = 0
b = 0
c = 0

while a < 190 and b < 140 and c < 110: # <-- This condition here
a = 0
b = 0
c = 0

for i in range(1, 465):
v = random.randint(1, 3)

if v == 1:
a = a + 1
elif v == 2:
b = b + 1
else:
c = c + 1

result = ""
result += "a: " + str(a) + "\n"
result += "b: " + str(b) + "\n"
result += "c: " + str(c) + "\n"

print (result)
``````

I want to loop this until a is above 190 AND b above 140 AND c above 110 but it stops everytime after the first run.

Can someone help me there?

You could change the logically slightly and use an infinite loop that you then `break` out of when your conditions are met:

``````while True:
# do stuff
if a >= 190 and b >= 140 and c >=110:
break
``````

Your original logic terminated if any of the conditions were met. For example, this loop exits because `a` is no longer `True` after the first iteration:

``````a = True
b = True
while a and b:
a = False
``````

This loop is infinite because `b` is always `True`:

``````a = True
b = True
while a or b:
a = False
``````

You could use `or` instead of `and` for your initial `while` loop, but I find the `break` logic far more intuitive.

Source (Stackoverflow)