pythoncoin-flipping

Coinflip until 50/50


"pretty new programmer here" i'm trying to do a coin-flip code that flips a coin 100 times and gives me the heads or tails total value, but i would want to keep fliping untill its 50/50.

I have the coin-flip but i'm in an infinite loop i cant get out of


heads = 0
tails = 0
tries = 0

while heads != 50 and tails != 50:
    for i in range(100):
        x = random.randint(0,1)
        if x == 1:
            heads += 1
        else:
            tails += 1
    print(heads,tails)
    tries += 1
    tails = 0
    heads = 0

print(tries)

i would like it to display the heads and tails every time and then the iterations it took to achieve 50/50.

for example

55 45

52 48

47 53

51 49

53 47

40 60

45 55

42 58

51 49

46 54

54 46

42 58

51 49

45 55

48 52

50 50

I know the answer must be so easy but i just cant figure it out.

thanks in advance


Solution

  • Set heads and tails to 0 at the beginning of the while loop, not the end, otherwise both will always be 0 at the moment when the while condition is checked.