Home > Blockchain >  I want to end the while loop in python when both the conditions are false but it stops when only one
I want to end the while loop in python when both the conditions are false but it stops when only one

Time:05-06

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))

CodePudding user response:

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.

CodePudding user response:

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))

'''

  • Related