I'm working on a quiz at the moment. I was wandering whether anyone can help me with an error i keep receiving. Here is my code:
num1 = num = 0
import random
questions = ["What is RAM?","what is ROM","What is a bundle of wires
carrying data from one component to another?","What does the control unit
do?"]
ans = [["Random access memory","real access memory","read access
memory","readable access memory","A"],["Readable object memory","Random
object memory","Read only memory","Read object memory","C"],
["Bus","Hardware","System software","Embedded systems","A"],["You type on
it","It sends out control signals to other components","It calculates
arithmetic problems","Regulates time and speed of computer functions","D"]]
for index in range(0, len(questions)):
val = [0, 1, 2, 3]
index = random.choice(val)
print(questions[index])
print("\nA:",ans[index][0],"\nB:",ans[index][1],"\nC:",ans[index]
[2],"\nD:",ans[index][3],"")
pa = input("What is your answer?")
if pa == ans[index][4]:
num1, num = num1 + 1, num + 1
print("Correct!\nYou have got",num1,"out of",num,"correct so far\n")
questions.remove(questions[index])
ans.remove(ans[index])
val.remove(index)
else:
num = num + 1
print("incorrect!\nThe correct answer was",ans[index][4],"Your
correct questions are Your incorrect questions are")
I'm trying to make it so that it asks the questions in a random order, and doesn't keep giving them questions with other questions answers. Anyone know how that could be done? Would appreciate the help.
Use random.shuffle
for the indices:
>>> sequence = list(range(len(questions)))
>>> random.shuffle(sequence)
>>> sequence
[2, 0, 3, 1, ....]
Then pick questions with
for index in sequence:
question = questions[index]
I'd recommend consolidating the questions and answers into a single list; a list of tuples.
questions = [('What is RAM?', 'random access memory'), ('What is ROM?', 'read-only memory')]
Then to pick out a question, run
question = random.choice(questions)
Put together, it'll look pretty close to your original script:
import random
questions = [('What is RAM?', 'random access memory'), ('What is ROM?', 'read-only memory')]
while questions:
question = random.choice(questions)
print(question[0])
user_response = input('Reponse> ')
if user_response == question[1]:
print('Correct!')
questions.remove(question)
else:
print('Wrong!')
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.