Function does not recognize variable

Asked

Viewed 39 times

1

p1pos = 0
def rodada(a):
    if a == 1:
        p1pos += sortear()
        print('Posição do P1: ', p1pos)
        acerto = pergunta()
        if p1pos in cAvanco and acerto == True:
            p1pos += 1
            print('Mais uma casa. P1: ', p1pos)
        elif p1pos in cRetro and acerto == True:
            p1pos = p1pos
            print('Casa de retrocesso. Mas você acertou. P1: ', p1pos)
        elif p1pos in cRetro and acerto == False:
            p1pos -= 1
            print('Você errou em uma casa de retrocesso. Posição P1: ', p1pos)
        else:
            print('Casa neutra, sua posição continua a mesma. P1: ', p1pos)

Error: Unboundlocalerror: local variable 'p1pos' referenced before assignment

  • The variable is defined outside the scope of the function, so it is read-only, you cannot change its content and hence the error. You can send it as an argument of its function, play all the logic inside a class or else (something little recommended) declare it as global.

  • If I put var as argument, when calling the function, it will be able to edit the value of the variable that is outside the function?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.