我正在创建一个问答代码,我需要问题函数来返回resposta_usuario值,但这没有发生
问答游戏代码
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)
我期望resposta_usuario值的输出,但实际输出是
NameError:名称'resposta_usuario'未定义
答案 0 :(得分:1)
您在函数内部创建了变量,因此它的作用域仅在函数内部可用,函数外部的代码看不到它或nae引用它。您的函数返回值,但是您不存储返回值。因此,要么打印将打印返回值的函数调用
print(pergunta())
或将函数的返回值存储在函数外部作用域中的变量中
resposta_usuario = pergunta()
print(resposta_usuario)
答案 1 :(得分:0)
您需要打印函数的返回值。 module.exports = {
dotenv: resolveApp('.env'),
appPath: resolveApp('.'),
appBuild: resolveApp('build'),
appPublic: resolveApp('public'),
appHtml: resolveApp('public/mynewawesomeindexfile.html'), //Change only this line
appIndexJs: resolveModule(resolveApp, 'src/index'),
appPackageJson: resolveApp('package.json'),
appSrc: resolveApp('src'),
appTsConfig: resolveApp('tsconfig.json'),
appJsConfig: resolveApp('jsconfig.json'),
yarnLockFile: resolveApp('yarn.lock'),
testsSetup: resolveModule(resolveApp, 'src/setupTests'),
proxySetup: resolveApp('src/setupProxy.js'),
appNodeModules: resolveApp('node_modules'),
publicUrl: getPublicUrl(resolveApp('package.json')),
servedPath: getServedPath(resolveApp('package.json')),
};
在您使用的范围内未定义:
resposta_usuario