[Tutor] Issue w/ program: Flip a coin and count heads and tails

Bhanu Pratap Singh bhanu.bais at gmail.com
Fri May 24 14:27:52 CEST 2013


Hi Rafeal,

You have called random function two times. It must be called single time and check if it produced 1 or 2. See my code.
/* code
---------------------------*/
import random
print("""
	This program flips a coin 10 times.
	It then counts the number of heads and tails.
	""")
flips = 0
heads = 0
tails = 0
while flips < 10:
	rand = random.randint(1, 2)
	if rand == 1:
		heads += 1
		print("We've got " + str(heads) + " heads here.")
	elif rand == 2:
		tails += 1
		print("We've got " + str(tails) + " tails here.")
	flips = flips + 1
/*----------------------------------- */

-----Original Message-----
From: Tutor [mailto:tutor-bounces+bhanubais=gmail.com at python.org] On Behalf Of Bod Soutar
Sent: Friday, May 24, 2013 4:37 PM
To: Rafael Knuth
Cc: Tutor at python.org
Subject: Re: [Tutor] Issue w/ program: Flip a coin and count heads and tails

On 24 May 2013 12:01, Rafael Knuth <rafael.knuth at gmail.com> wrote:
> Hello,
>
> I am writing a program in Python 3.3.0 which flips a coin 10 x times 
> and then counts the number of heads and tails. It obviously does 
> something else than I intended, and I am wondering what I did wrong:
>
> import random
>
> print ("""
>
> This program flips a coin 10 times.
>
> It then counts the number of heads and tails.
>
> """)
>
> flips = 0
>
> heads = 0
>
> tails = 0
>
> while flips < 10:
>
>     flips = flips + 1
>
>     if random.randint(1,2) == 1:
>
>         heads = heads + 1
>
>         print("We've got " + str(heads) + " heads here."
>
>     if random.randint(1,2) == 2:
>
>         tails = tails + 1
>
>         print("We've got " + str(tails) + " tails here.")
>
> This is what I get as output:
>
> This program flips a coin 10 times.
>
> It then counts the number of heads and tails.
>
> We've got 1 tails here.
>
> We've got 1 heads here.
>
> We've got 2 tails here.
>
> We've got 2 heads here.
>
> We've got 3 tails here.
>
> We've got 3 heads here.
>
> We've got 4 tails here.
>
> We've got 5 tails here.
>
> We've got 4 heads here.
>
> We've got 6 tails here.
>
> We've got 7 tails here.
>
> We've got 5 heads here.
>
> Can anyone help?
>
> Thank you so much!
>
> All the best,
>
>
>
> Rafael
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Hint: Look at your second if statement

Bodsda
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list