[Tutor] Flip the coin 10x and count heads and tails: It works now!

Steven D'Aprano steve at pearwood.info
Sat May 25 15:13:38 CEST 2013


On 25/05/13 19:25, Rafael Knuth wrote:

> flips = 0
> heads = 0
> tails = 0
>
> while flips < 10:
>      flips = flips + 1

Don't do this. It's not 1971 any more, we've had for loops for forty years :-)

Use while loops when you don't know how many loops you need. When you know how many loops you will have, use a for loop.

for flip in range(10):
     print(flip)

will print 0 1 2 3 ... 9 which makes ten loops altogether. If you want to start counting at 1 instead of 0, use:

for flip in range(1, 11):
     print(flip)

which will print 1 2 3 ... 9 10.


There's no need to count the number of heads and tails separately, since every loop is guaranteed to give either head or tails. So just count the number of heads, then the number of tails will be ten less the number of heads.




-- 
Steven


More information about the Tutor mailing list