On 11/21/2015 06:44 PM, Larry Hudson wrote:
On 11/20/2015 07:30 PM, Dylan Riley wrote:
i am learning python and was tasked with making a program that flips a coin 100 
times and then
tells you
the number of heads and tails.

[snip]
<original code>
import random

heads = int("1")
tails = int("2")
flips = 100
headscount = 0
tailscount = 0

while flips != 0:
     flips -= 1

result = random.randint(heads, tails)
if result = heads:
     headscount += 1
else:
     tailscount += 1


print(headscount, tailscount)
[snip]
</original code>

It doesn't run because it if full of errors, which have already been discussed 
by others.

I just wanted to show you a (radically) different approach that you can study 
(or not... your
choice).  I'm leaving out your heading and just showing the heart of the 
program.  I am not
necessarily recommending this, I just wanted you to see a different way of 
looking at the
problem.  Except for the initialization and printing of the results, the entire 
thing is done in
one two-line for loop.

<code>
from random import randint

#  Put your heading text here...

HEADS = 0
TAILS = 1    #  Note:  Python _convention_ is to upper-case constants.
counts = [0, 0]

for flips in range(100):
     counts[randint(0, 1)] += 1

print('Number of heads: ', counts[HEADS])
print('Number of tails: ', counts[TAILS])
</code>

Note that the HEADS and TAILS constants are only used in one place (the final 
print functions),
you could simply leave them out and directly use 0 and 1 in those final 
print()s.

      -=- Larry -=-


I purposely didn't give any explanation of this code in my original message because I wanted to allow people (particularly the OP) a chance to figure it out by themselves. But here's a bit of explanation...

The counts variable is a two-element list. It's usage is, the count of heads is counts[0] and the count of tails is counts[1] -- or equivalently, counts[HEADS] and counts[TAILS]. Both values are initialized to 0.

The body of the for loop is the very terse (and confusing?) expression:
    counts[randint(0, 1)] += 1

But if you break it down and look at the pieces individually, it's not too hard 
to understand.
1. randint(0, 1) gives a random value of either 0 or 1.
2. counts[...] gives you access to the heads count or tails count (... is the 0 or 1 from the randint() function).
3. counts[...] += 1 increments the appropriate counter value.

Broken down that way it’s not too hard to understand, is it?   :-)

-=- Larry -=-

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to