Search code examples
pythonpython-3.xnameerror

Why do I get an error "name 'play' is not defined" when I think it is?


Full error:

line 10, in <module>
    colour = play()
NameError: name 'play' is not defined

I can't seem to find a reason for this issue anywhere on here. I am trying to assign the returned string to the variable colour but it is refusing to recognise the function "play".

import random
Funds = 10
Bet = "Red"
betsequence = [0,0,0,0,0,0,0,0,0,0,0,0,0,0]
counter = -1
totalcount = 0

while(Funds > 0):
    counter = counter + 1
    colour = play()
    if colour == Bet:
        Funds = Funds+(betsequence[counter]*2)
        counter = -1
    else:
        Funds = Funds-betsequence[counter]
    print(colour)
    totalcount = totalcount

def play():
    random.seed(a=None, version=2)
    rannum = random.uniform(0,1)
    result = rannum*14
    if (result > 1) and (result < 8):
        return "Red"
    elif result < 1:
        return "Green"
    else:
        return "Black"

Solution

  • You need to define the name before it is first used. In your case, moving the definition of play to before the while loop will solve the issue.