[Tutor] Need help solving this problem
ayyaz
ayyaz84 at gmail.com
Thu Jun 11 02:27:07 CEST 2009
Raj Medhekar wrote:
> I have been teaching myself Python using a book. The chapter I am on
> currently, covers branching, while loops and program planning. I am
> stuck on on of the challenges at the end of this chapter, and I was
> hoping to get some help with this. Here it is:
>
> Write a program that flips a coin 100 times and the tells you the number
> of heads and tails.
>
> I have tried to think about several ways to go about doing this but I
> have hit a wall. Even though I understand the general concept of
> branching and looping, I have been having trouble writing a program with
> these. I look forward to your reply that will help me understand these
> structures better.
>
> Sincerely,
> Raj
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
A very simple solution
import random # you need to import this module to generate random
# numbers
heads = 0; #init number of heads;
tails = 0; #init number of tails;
cnt = 0 # variable to store number of coin tosses
while cnt<100: # we want this loop to 100 times
toss = random.randrange(0,2,1) # this line will
randomly choose # between 0 and 1
if toss == 0:
tails += 1 # if the random generator gives 0, then we
increase # count of tail by one
else:
heads += 1 # if the random generator gives 1, then we increase
# count of head by one
cnt += 1 # increase count of coin toss by one
print "Number of heads", heads # print the number of heads
print "Number of tails", tails # print the number of tails
raw_input("\nPress enter to exit")
More information about the Tutor
mailing list