-2
def coin():
    print random.randint(0,1)
    if (coin() == 0):
        return Heads
    else:
        return Tails

coin_flip()

I just keep getting a series of errors. If I just end the code at the second line, then it properly returns a 0 or 1. So I thought if I did an if/else code, it should return proper names. But to no avail. I'm also trying to do it with this style of code, not just make any coin toss code. Thanks

2
  • And where is coin_flip() defined?
    – Martijn Pieters
    Nov 2, 2014 at 4:27
  • You're printing the random number, but you're not assigning it to a variable that you can test. And your if statement is just calling your function again.
    – Barmar
    Nov 2, 2014 at 4:29

3 Answers 3

4

I'm taking a guess here, but I think what you're trying to do is to define coin_flip rather than coin. If I understand correctly, here's what you should have written:

def coin_flip():
    coin = random.randint(0,1)
    if coin == 0:
        return 'heads'
    else:
        return 'tails'

and then you could call it later using coin_flip().

What's going on in the function is that you're assigning a value of 0 or 1 to the name coin. If that value is 0, you return the string 'heads'. Otherwise you return the string 'tails'.

2
  • Wait, what does the underscore represent in python? I've mainly done R stuff, in which underscores or whatever are just variable names. But an underscore does something in python so that "coin_flip" doesn't just represent a variable name? If "flip" like a command or something?
    – Hutchins
    Nov 2, 2014 at 6:11
  • 1
    The underscore is just a normal part of the function name. Nothing special about it. You can even call a variable something like ________ (that's not a good idea, of course).
    – Matthias
    Nov 2, 2014 at 8:12
1

You have infinite recursion in your code. If you trace through the execution you get :

call coin()
print
call coin()
print
call coin()
....
out of memory at some point
1
  • Yes, but why does he recurse infinitely? This doesn't tell him anything about what's caused the issue you're pointing out.
    – furkle
    Nov 2, 2014 at 5:18
-1

You probably want to store the value returned by random.randint(0,1) in a variable, say val. Then use val in your if condition.

if (val == 0):
    return Heads
else:
    return Tails

At present your code is recursing infinitely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.