0

i am writing a program about coin flips i want the user to enter number and for the program to flip a coin that many times.

once the user gives number the program stops

this is what i have

import random
flips = 0
heads=0
tails=0
numFlips = raw_input("Flips ")
while flips < numFlips:
    flips += 1
    coin = random.randint(1, 2)
    if coin == 1:
        print('Heads')
        heads+=1
    if coin == 2:
        print ('Tails')
        tails+=1
total = flips
print(total)
print tails
print heads
  • 3
    and your question is? :) – Tymoteusz Paul Oct 22 '13 at 13:28
  • Please try to follow the style guidelines described in [PEP8](http://www.python.org/dev/peps/pep-0008/) and keep your code consistent. For example, mixing `print(x)` and `print x` is an incredibly bad idea (you should use whatever is appropriate for your python version, i.e. `print x` for py2 and `print(x)` for py3) – ThiefMaster Oct 22 '13 at 13:30

2 Answers2

2

numFlips is a str. You have to convert it to an int first.

numFlips = int(raw_input("Flips "))

Otherwise, your check flips < numFlips will not work, since all ints are 'less than' any string.

(Also, you want to add some error-handling for the case the user enters something other than an integer)

Community
  • 1
  • 1
sloth
  • 99,095
  • 21
  • 171
  • 219
-1

On line

numFlips = raw_input("Flips ")

raw_input() reads a string : http://docs.python.org/2/library/functions.html#raw_input

Convert it to integer by doing int(raw_input("Flips "))

You can also use input() evaluates the string to a python expression, which in this case would evaluate to an int.

EDIT: As pointed out by @bruno desthuilliers, it is unsafe to use input() and should rather just convert the raw_input() to int.

Bharat
  • 2,960
  • 2
  • 38
  • 57
  • 2
    And that's a _very_ wrong solution. `input` doesn't "evaluates the string to an int", it evaluates the string as a Python expression, whatever it is, including a call to "os.system('rm -rf /')". `input` is unsafe. Don't use `input`. Do the RightThing and convert the input to what the program expects. – bruno desthuilliers Oct 22 '13 at 13:36
  • Note that you could/should use `ast.literal_eval` (instead of `input`/`eval`), which will safely evaluate to strings, numbers, tuples, lists, dicts, booleans, and None. – sloth Oct 22 '13 at 13:48