简体   繁体   中英

wrote a simple quiz code using two functions in python but a list is not defined

Designed a simple trivia quiz using 2 functions, but I got an error,how can I fix this?: 1 Traceback (most recent call last): File line 31, in run_quiz(Qlist) NameError: name 'Qlist' is not defined

Here is the code: enter image description here ***from random import shuffle print('Welcome to the fun quiz!')

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):
'''This function shuffles the quiz bank and create a question list for the users to answer'''
shuffle(lines)
Qlist=lines[:numQ]
return Qlist questions(numQ)

def run_quiz(Qlist):
'''Ask the user questions, determine whether the answer is correct, and count the correct answers.'''
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(Qlist)***

You can use the return value like so. As Qlist is returned from questions, you call that function and pass it as a parameter to run_quiz

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM