[Tutor] Flip a coin

Mitya Sirenef msirenef at lightbird.net
Tue Apr 9 16:30:20 CEST 2013


On 04/09/2013 07:50 AM, Najam Us Saqib wrote:
> Hi,
 >
 > This program is killing me, I have been working on it for last 3 
hours, I have tried my best but can't make it work, please help me out.
 >
 > The Problem:
 >
 > Create a program that flips a coin 100 times and than tells you the 
number of tails and heads.
 >
 > My code:
 >
 > # Flip a coin
 >
 > import random
 >
 > flip_coin = 100
 > head = ""
 > tail = ""
 > n_head = 0
 > n_tail = 0
 > the_num = (raw_input("Press enter key to flip the coin!"))
 >
 >
 > #raw_input("Please Flip the Coin")
 >
 > while flip_coin != 100:
 >     flip_coin = random.randrange(100) +1
 >     if flip_coin <= 50:
 >
 >      print "head"
 >
 >     else:
 >      print "tail"
 >
 >     the_num = (raw_input("Press Enter to flip the coin"))
 >     n_head += 1
 >     n_tail += 1
 >
 >
 >
 > print "The total numbers of heads are" ,n_head
 > print "The total numbers of tails are" ,n_tail
 >
 > raw_input("\n\nPress the enter key to exit, thank you")
 >
 > Thank you very much, looking forward to hear from you.
 >
 > Regards,
 > Najam.
 >


You shouldn't start with writing code when you're not clear on how it
needs to work -- instead, start with pseudo code. In the same way, if
you can lift 200lbs you can start with 100lbs and then work your way up.

The pseudo code is a lot simpler to write than code:

# assume 0 is heads and 1 is tails

num_heads = num_tails = 0

- repeat 100 times:
     get input from user
     if input == quit: break loop

     flip = random integer out of 0 and 1

     if flip:
         print tails
         num_tails += 1
     else:
         print heads
         num_heads += 1
     print num_heads, num_tails

print Exiting...


To find out how to pick a random integer, see:

http://docs.python.org/2/library/random.html


  -m


-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/



More information about the Tutor mailing list