I am creating a Q&A code and I need the question function to return the resposta_usuario value, but it is not happening
Q&A game code
perguntas = open('perguntas.txt','r')
respostas = open('respostas.txt','r')
respostas_linha = respostas.readlines()
c = 0
score = 0
def pergunta():
#Mostra a pergunta guardada no perguntas.txt e retorna a resposta do usuário
for linhas in perguntas:
if linhas == '\n':
resposta_usuario = input('Qual sua resposta?: ')
return resposta_usuario <------ THE PROBLEM IS HERE
else:
print (linhas)
def verificar(resposta_usuario):
if resposta_usuario == respostas_linha[c]:
print('Resposta Correta')
c=+c
score = score + 10
pergunta()
else:
print('Fim de jogo!')
print('Tente novamente')
pergunta()
print(resposta_usuario)
I expect the output of resposta_usuario value, but the actual output is
NameError: name 'resposta_usuario' is not defined
2 Answers 2
you create the variable inside the function so the scope of it is only available inside the function, code outside the function cant see it or refer to it by nae. Your function returns the value but you dont store the return value. So either print the function call which will print the return value
print(pergunta())
or store the return value from the function in a variable in the scope outside the function
resposta_usuario = pergunta()
print(resposta_usuario)
Comments
You need to print the return value of the function. resposta_usuario is undefined in the scope you've used it:
print(pergunta())
print(pergunta()), you need to print the returned value, not the variable name (which exists only in thedefscope).forloop to be in line with yourdefprint(resposta_usuario)The variable is defined in the function as a local - it will not be available to you outside the function. You need to do something like:res = pergunta(); print(res)