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.
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.
– João Carlos Agostini
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
– Augusto Vasques
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 lavraglobal
within the scope of the function to warn the interpreter not to recreate a local version of the variable.– Augusto Vasques