[Tutor] Beginner - explaining 'Flip a coin' bug
Steven D'Aprano
steve at pearwood.info
Wed Feb 12 22:14:51 CET 2014
On Wed, Feb 12, 2014 at 03:25:22PM +0000, Marc Eymard wrote:
> I want to emulate a coin flip and count how many heads and tails when
> flipping it a hundred times.
In my last reply, I said I'd next give you some pointers to
improve the code. If you'd rather work on it yourself first, stop
reading now!
In your working code, you have (in part):
count_heads = 0
count_tails = 0
count_flips = 0
while count_flips != 100:
coin_side = random.randint(1,2)
count_flips += 1
if coin_side == 1:
count_heads += 1
#count_flips += 1
else: count_tails += 1
#count_flips += 1
The first thing to notice is that by the logic of the task, each flip
must be either a Head or a Tail, so the number of Heads and the number
of Tails should always add up to the number of flips. So you don't need
to record all three variables, you only need two of them.
The second thing is that since the number of flips is incremented by one
every single time through the loop, regardsless of what happens, you
don't need to manually increment that. You can get Python to do the
counting for you, using a for-loop:
for count_flips in range(1, 101):
coin_side = random.randint(1,2)
if coin_side == 1:
count_heads += 1
At the end of the loop, you will have count_flips equal to 100 (can you
see why?) and the number of Tails will be count_flips - count_heads.
--
Steven
More information about the Tutor
mailing list