+ 1

Flip coin till 3 heads or 3 tails in a row - help with my code?

Hi guys - I wrote this code (named "3heads" in Code Playground) where the computer should flip a coin consecutively till they get 3 of the same results in a row. Technically it runs, but I don't think it runs right because my "while" loop is wrong. Everytime, I get results in less than 5 flips, so what am I doing incorrectly? Code is named "3heads" in the playground - I don't know how to link it directly here. Thanks! ------ #run program till you get 3 heads or 3 tails in a row consecutively import random sides = ["heads", "tails"] i = 0 while i<10: flip1 = random.choice(sides) flip2 = random.choice(sides) flip3 = random.choice(sides) if flip1 != flip2 and flip2 != flip3: print(flip1, flip2, flip3) i += i elif flip1 == flip2 and flip2 == flip3: print(flip1, flip2, flip3) break

2nd Jun 2017, 3:51 PM
Nasheed Shams
Nasheed Shams - avatar
6 Antworten
+ 7
Try this: import random sides = ['heads', 'tails'] i = 0 while True: flip1 = random.choice(sides) flip2 = random.choice(sides) flip3 = random.choice(sides) i += 1 print(flip1, flip2, flip3) if flip1 == flip2 == flip3: break print('After', i, 'tries')
2nd Jun 2017, 5:18 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
2nd Jun 2017, 8:32 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 4
True. I thought we were looking for triplets being the same. As a matter of fact, looping until three in a row are the same is not much harder...
2nd Jun 2017, 8:20 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 2
@kuba: I was looking for triplets being the same. But now, I'm gonna try to solve 3 in a row.
2nd Jun 2017, 8:22 PM
Nasheed Shams
Nasheed Shams - avatar
0
@Kuba: this will not detect 3 in a row in: heads tails tails tails heads heads
2nd Jun 2017, 7:57 PM
Igor B
Igor B - avatar
0
Hey! Cool idea for the project—you're close, but the issue is that your current code flips three coins at once every time, rather than flipping one at a time and checking for three in a row. That’s why you often get results in fewer flips—it’s not simulating real consecutive coin flips. Instead, try flipping one coin at a time inside the loop and tracking how many times the same result appears in a row. Here’s a quick example of how you could structure it: import random sides = ["heads", "tails"] count = 0 last_flip = None total_flips = 0 while count < 3: flip = random.choice(sides) print(flip) total_flips += 1 if flip == last_flip: count += 1 else: count = 1 last_flip = flip print("It took", total_flips, "flips to get 3 in a row!") This version flips until it gets three of the same in a row. Hope that helps—and if you're ever unsure, you can always flip a coin visit here: https://flipacoinonline.com/ to test randomness outside the code 😄 Let me know if you want help linking your Code Playground file too!
1st May 2025, 9:01 PM
Jasson Adder