0

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

3
  • print(pergunta()), you need to print the returned value, not the variable name (which exists only in the def scope). Commented Oct 3, 2019 at 9:47
  • Is this indentation correct? Your function body should be 1 level indented, what you posted shows the for loop to be in line with your def Commented Oct 3, 2019 at 9:47
  • The error is coming from here. print(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) Commented Oct 3, 2019 at 9:51

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

You need to print the return value of the function. resposta_usuario is undefined in the scope you've used it:

print(pergunta())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.