Why won't my counter loop work?

print(“Problem 7”)
for i in range (5):
j = random.randint(0,1)
if j == 0:
j = “heads”
if j == 1:
j = “tails”
count = 0
while j == 0:
count += 1
print(“You got”, count, “tails”)

Why doesn’t this work? EVERY TIME I try this, I only get 0.

Hello @teaganteagan ,

Welcome to the forums!

Try inserting a print(j) after your j = random.randint(0,1) to view the values being generated.

For next time, a couple helpful tips:

1 Like

you probably want to move the count = 0 to outside the loop so count isn’t being reset to 0 each time the loop runs [each iteration].
Also, you had that if j is 0, then j gets changed to be "heads",
so you could never have j being 0 after that code (it would be "heads" instead)
you could fix that by checking j == "heads" instead of j == 0 in the code after that, or just use a different variable for "heads" and "tails".

Also, while j == 0 would give you an infinite loop there (because j would start out as 0, and the loop would keep running over and over as long as the value of j is 0, but tthe value of j isn’t changed to anything else inside the loop, so the while loop just keeps repeating.
Instead, if j == 0 would be more appropriate - it only runs once.

(spoiler below - don’t look until after you’ve tried it yourself more first)

import random count = 0 for i in range (5): j = random.randint(0,1) if j == 0: k = "heads" if j == 1: k = "tails" if j == 0: count += 1 print("You got", count, "tails")
1 Like