A for loop should return a list of 10 values. It returns a list with a random number of items

Issue

I´m doing the coin flip challenge from the automate the boring stuff course.
I have to calculate the odds of a 6 heads or 6 tails streak occuring for a total of 100 streaks.

So, first step is to produce a list with each item assigned either H or T so in the second step we can search for 6 streaks in the list.
As i am starting with python and coding, when i am having trouble with a challenge, i like to do a practice run. Write a small program using concepts that i know i will need to make the final program.

 import random

Heads=0
Tails=0


exper=[]
for i in range(10):
    if random.randint(0, 1)==0:
        exper.append('H')
        Heads=Heads + 1
    if random.randint(0, 1)==1:
        exper.append('T')
        Tails = Tails + 1
    


print (exper)
print (Heads)
print(Tails)

An example of the desired output would be something like

['H','T','H','T','H','T','H','T','H','T']

i dont know if im doing something wrong, but it should work properly.
My output is a list with T´s and H´s in it but the length of the list is random…sometimes its a list with 2 items, others with 10, or even 14.

Thanks in advance and i hope i have explained it well. First question here in this site.

Solution

You are calling random.randint twice in each iteration of the loop. It’s possible each one produces 1 or 0. Consider what happens if the first call to random.randint produces a 0 and the next one produces a 1. This would cause both an H and a T to be appended to the list in the same iteration of the loop. The opposite can happen too resulting in no value appended.

So in each iteration of the loop you can append zero, one, or two values. Since if it’s not heads, it must be tails, one options would be to add an else instead of another call to random.randint.

import random

Heads=0
Tails=0

exper=[]
for i in range(10):
    if random.randint(0, 1)==0:
        exper.append('H')
        Heads=Heads + 1
    else: # if it's not heads, it must be tails
        exper.append('T')
        Tails = Tails + 1
    


print (exper)
print (Heads)
print(Tails)

Which should consistently produce 10 values:

['T', 'T', 'T', 'H', 'H', 'H', 'T', 'H', 'T', 'H']
5
5

Answered By – Mark

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.