Reputation: 5
questions = ["Python is a coding language \n [1] True \n [2] False", "There are this many coding languages \n [1] 5 \n [2] 3 \n [3] 17 \n [4] Over 500 \n", "question 3", "question 4", "question 5", "question 6", "question 7", "question 8", "question 9", "question 10",]
answers = ["1", "1", "1", "1", "1", "1", "1", "1", "1", "1",]
asked_questions = []
Number = 0
import random
def quiz():
global questions
global answers
global asked_questions
global Number
while Number != 10:
randomnumber = random.randint(0,9)
random_question = questions[randomnumber]
asked_questions.append(randomnumber)
for alreadyaskedquestions in range(len(asked_questions)):
if randomnumber == asked_questions[alreadyaskedquestions-1] and asked_questions[alreadyaskedquestions] != 0:
del(asked_questions[-1])
quiz()
print(random_question)
answer = input("")
Number += 1
if answer == answers[randomnumber]:
print("correct")
else:
print("wrong")
quiz()
I am creating a quiz program that asks 10 questions in a random order. I want the function to stop after 10 questions have been asked, but the while loop continues to run even after it's condition has been met. I have tried adding print statements and found that in my program, the code does not run the lines before the for loop when 10 questions have been asked, but I'm not sure why or how this would fix the issue. Thanks in advance
Upvotes: 0
Views: 72
Reputation: 425198
Use a question
class that has the question text and the answer. Put them a list and randomise the order:
import random
random.shuffle(questions)
Then ask them looping over the shuffled list.
Upvotes: 1
Reputation: 2288
Here's a bit of a different way of achieving what you are trying to do:
import random
def quiz(questions, answers):
quiz_remaining = [{'q': questions[i], 'a': answers[i]} for i in range(0,len(questions))]
question_count = 0
while question_count < 10:
question_count += 1
random_number = random.randint(0,len(quiz_remaining)-1)
random_quiz = quiz_remaining[random_number]
del quiz_remaining[random_number]
print(random_quiz['q'])
answer = input("")
if answer == random_quiz['a']:
print("correct")
else:
print("wrong")
questions = ["Python is a coding language \n [1] True \n [2] False", "There are this many coding languages \n [1] 5 \n [2] 3 \n [3] 17 \n [4] Over 500 \n", "question 3", "question 4", "question 5", "question 6", "question 7", "question 8", "question 9", "question 10",]
answers = ["1", "1", "1", "1", "1", "1", "1", "1", "1", "1",]
quiz(questions, answers)
There are some differences between it and your code:
Upvotes: 0