[Tutor] Giving a name to a function and calling it, rather than calling the function directly

bob gailer bgailer at gmail.com
Sun Sep 5 03:32:58 CEST 2010


  On 9/4/2010 10:14 AM, lists wrote:
> Hi folks,
>
> I'm new to Python, I'm working my way through some intro books, and I
> have a question that I wonder if someone could help me with please?
>
> This is my attempt at solving an exercise where the program is
> supposed to flip a coin 100 times and then tell you the number of
> heads and tails.
>
> ATTEMPT 1 returns:
>
> The coin landed on tails 100 times
>
> The coin landed on heads 0 times
>
> ATTEMPT 2 returns:
>
> The coin landed on tails 75 times
>
> The coin landed on heads 25 times
>
> I expected to see the result in attempt 2. I don't fully understand
> why the results are different however. Is it because Python only runs
> the randint function once when I call it by the name I assigned to it
> in attempt 1, but it runs the function fully on each iteration of the
> loop in attempt 2? Why are these two things different?
>
> Thanks in advance,
>
> Chris
> ------------------------------------------------------------------
> ATTEMPT 1
> ------------------------------------------------------------------
> import random
>
> heads = 0
> tails = 0
> tossNo = 0
> toss = random.randint(1,2)
>
> while tossNo<= 99:
>      if toss == 1:
>          heads += 1
>          tossNo += 1
>      elif toss == 2:
>           tails += 1
>           tossNo += 1
>
> print "The coin landed on tails " + str(tails) + " times \n"
> print "The coin landed on heads " + str(heads) + " times \n"
>
> ------------------------------------------------------------------
> ATTEMPT 2
> ------------------------------------------------------------------
> import random
>
> heads = 0
> tails = 0
> tossNo = 0
>
You should have only 1 call to randint in the loop
> while tossNo<= 99:
>      if random.randint(1,2) == 1:
>          heads += 1
>          tossNo += 1
>      else:
>           tails += 1
>           tossNo += 1
>
> print "The coin landed on tails " + str(tails) + " times \n"
> print "The coin landed on heads " + str(heads) + " times \n"

You can also simplify:

import random
heads = 0
tosses = 100
for i in range(tosses):
     heads += random.randint(0,1)
print "The coin landed on tails " + str(tosses - heads) + " times \n"
print "The coin landed on heads " + str(heads) + " times \n"

Or even simpler:

import random
tosses = 100
heads = sum(random.randint(0,1) for i in range(tosses))
print ...


-- 
Bob Gailer
919-636-4239
Chapel Hill NC



More information about the Tutor mailing list