使用python中的两个函数编写了一个简单的测试代码,但没有定义列表

2024-04-29 07:31:42 发布

您现在位置:Python中文网/ 问答频道 /正文

使用2个函数设计了一个简单的琐事测验,但我遇到了一个错误,我如何修复它?:1回溯(最近一次呼叫最后一次): 文件第31行,在 运行测试(Qlist) 名称错误:未定义名称“Qlist”

代码如下: enter image description here ***从随机导入洗牌 打印(“欢迎参加有趣的测验!”)

filename=input('请输入文件名(quick.txt)开始:')
将open(filename,'rb')作为f:
行=f.读行()

numQ=int(输入('您想回答多少个问题(10-15)?))

def问题(numQ):
''此函数洗牌测验库并创建供用户回答的问题列表'
洗牌(行)
Qlist=行[:numQ]
返回Qlist 问题(numQ)

def run_测验(Qlist):
''向用户提问,确定答案是否正确,并计算正确答案。'
右=0
对于Qlist中的行:

问题,rightAnswer=line.strip().split('\t')

回答=输入(问题+“”)

如果answer.lower()==rightAnswer:

打印('正确!')

右+=1

其他:

打印('不正确。正确答案是',正确答案)
返回打印('You got',right,'out',numQ,'which is',right/numQ*100',%.')运行测验(Qlist)***


Tags: 文件函数答案代码用户right名称def
1条回答
网友
1楼 · 发布于 2024-04-29 07:31:42

您可以像这样使用返回值。当从问题返回Qlist时,您可以调用该函数并将其作为参数传递给运行

filename=input('Please enter the filename(quiz.txt)to get started:' )
with open(filename,'rb') as f:
    lines=f.readlines()

numQ=int(input('How many questions would you like to answer (10-15)?'))

def questions(numQ):
    shuffle(lines)
    Qlist=lines[:numQ]
    return Qlist

def run_quiz(Qlist):
    right=0
    for line in Qlist:
        question, rightAnswer=line.strip().split('\t')
        answer=input(question+' ')
        if answer.lower()==rightAnswer:
            print('Correct!')
            right+=1
        else:
            print('Incorrect.The right answer is', rightAnswer)
    return print('You got',right,'out of',numQ,'which is',right/numQ*100,'%.')

run_quiz(questions(numQ))

相关问题 更多 >