Python - does not allow assigning value to the variable in if conditional, why?

Asked

Viewed 402 times

4

I did something in Python that is common to do in C and javascript, ie, give a value to a variable when an if condition is met. I’m sure that in Python it’s also possible to program in this way, but, I don’t know why, it hasn’t worked in the traditional way. The variable is not accepted. The code in question is as follows:

#variáveis globais
N = ''
nao = 1
def jogador(N):
    if N == '':
        return '', 1
    elif N == 'X' or N == 'x' or N == 'O' or N == 'o':
        if N == 'X' or N == 'x':
            nao = 0  <- aqui deveria haver esta variável, mas ela não é aceita, fica cinza no PyCharm
            return 'X', 0 <- solução usada para dar valor 0 à variável nao
        else:
            nao = 0 <- idem
            return 'O', 0 < solução usada para dar valor 0 à variável nao
    else:
        print('Letra errada!')
        print('Tente outra vez!')
        return '', 1

while nao: <- quando fica igual a 0 o while para, bom vcs sabem disso
    print('Qual você escolhe para jogar: X ou O? ')
    N = input()
    E, nao = jogador(N) <- solução encontrada para dar o valor 0 ao nao

The whole program comes down to this for now. I’m learning Python and I’m playing the old-fashioned game. Another thing, if does not accept any other type of variable. I can by var = 0 and it is not accepted. Does anyone have any explanation? Thank you.

1 answer

3


In Python the external variables referenced within a function are read-only global. If a variable that is global has a value assigned anywhere in the body of the function, it will be automatically recreated as local, unless which has been explicitly stated as global.

If you want to assign value to a global variable within a local scope use the keyword global before using the variable.

#variáveis globais
nao = 1

def jogador(N):
    global nao #Declarando a variável global para uso nese escopo
    N = N.strip().upper()
    if len(N) == 1:
      if N in 'XO':
        nao = 0  
        return N      
      print('Letra errada!')
      print('Tente outra vez!')
    return ''

while nao: 
    print('Qual você escolhe para jogar: X ou O? ')
    E = jogador(input())

Test the code in the Repl.it: https://repl.it/repls/BustlingCylindricalLinkedlist

But I personally am not in favor of global use within functions and methods:

def jogador(N):
    N = N.strip().upper() 
    if len(N) == 1:
      if N in 'XO':
        return N       
      print('Letra errada!')
      print('Tente outra vez!')
    return ''

while True: 
    print('Qual você escolhe para jogar: X ou O? ')
    E = jogador(input())
    if len(E) == 1: break

print(f'O jogador escolheu {E}')

Test the code in the Repl.it: https://repl.it/repls/WellwornMintyDatasets


References:

  • 1

    Augusto Vasques, thank you very much for your reply. I reviewed everything I read about scope in Python and did not see this information you brought me, which makes me worried about getting complete sources for this study of mine. Another thing that bothered me and made me sleep badly, was the way you solved the issue of N. Accustomed to C, I did something traditional in this language, but you showed me that I should think differently with python, which leaves me somewhat bereft of knowledge already accumulated, which is no longer useful. Thanks again.

  • 1

    Sorry to disappoint, but I don’t have a secret reading file on an emergency flash drive or hidden shelf on the bookcase. The only thing I read is the official language documentation you can read here and here

  • 1

    Yes, declare the nao = 1 outside the functions makes the global variable. But as I have already said if a variable that is global has a value assigned anywhere in the body of the function, it will automatically be recreated as local. To avoid this behavior we use the key lavra global within the scope of the function to warn the interpreter not to recreate a local version of the variable.

Browser other questions tagged

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