Reputation: 1
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)***
Upvotes: 0
Views: 424
Reputation: 2318
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))
Upvotes: 0