'I want to end the while loop in python when both the conditions are false but it stops when only one condition is false
Here's my code, the purpose is to generate an array with 10 randomly generated 0's and 10 randomly generated 1's. While loops stops working when 'a' is equal to 10 or 'b' is equal to then and I am not getting equal amount of 0's and 1's.
import random
a = 0
b = 0
numbers = []
while (a < 10 and b < 10):
x = random.randrange(2)
if x == 0:
numbers.append(x)
a+=1
elif x == 1:
numbers.append(x)
b += 1
print(a,b)
print(numbers, len(numbers))
Solution 1:[1]
You can do this,
import random
a = 0
b = 0
numbers = []
while True:
x = random.randrange(2)
if x == 0 and a < 10:
numbers.append(x)
a += 1
elif x == 1 and b < 10:
numbers.append(x)
b += 1
if a >= 10 and b >= 10:
break
print(x, a, b)
print(a, b)
print(numbers)
But if you just want 10 0's and 10 1's then there are better ways to do that.
Solution 2:[2]
It will work like this, I tried for couple of hours and found the solution.
import random
a = 0
b = 0
loop = True
numbers = []
while (loop):
x = random.randrange(2)
if x == 0 and a < 10:
numbers.append(x)
a+=1
elif x == 1 and b < 10:
numbers.append(x)
b += 1
if (a == 10 and b == 10):
loop = False
print(a,b)
print(numbers, len(numbers))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Zero |
Solution 2 | Avinash |