1

My task is to make a quiz using python, with questions being stored in an external file. However, I can not figure out how to get my questions to randomize and only display 10 at a time out of the 20 possible

I have tried using import random however the syntax random.shuffle(question) does not seem to be valid. I am not sure what to do now.

The question.txt file is laid out as:

Category
Question
Answer
Answer
Answer
Answer
Correct Answer
Explanation 

My code:

#allows program to know how file should be read
def open_file(file_name, mode):
    """Open a file."""
    try:
        the_file = open(file_name, mode)
    except IOError as e:
        print("Unable to open the file", file_name, "Ending program.\n", e)
        input("\n\nPress the enter key to exit.")
        sys.exit()
    else:
        return the_file

def next_line(the_file):
    """Return next line from the trivia file, formatted."""
    line = the_file.readline()
    line = line.replace("/", "\n")
    return line

#defines block of data 
def next_block(the_file):
    """Return the next block of data from the trivia file."""
    category = next_line(the_file)
    question = next_line(the_file)

    answers = []
    for i in range(4):
        answers.append(next_line(the_file))

    correct = next_line(the_file)
    if correct:
        correct = correct[0]

    explanation = next_line(the_file)
    time.sleep(1.5)

#beginning of quiz questions

def main():
    trivia_file = open_file("trivia.txt", "r")
    title = next_line(trivia_file)
    welcome(title)
    score = 0

    # get first block
    category, question, answers, correct, explanation = next_block(trivia_file)
    while category:
        # ask a question
        print(category)
        print(question)
        for i in range(4):
            print("\t", i + 1, "-", answers[i])

        # get answer
        answer = input("What's your answer?: ")

        # check answer
        if answer == correct:
            print("\nCorrect!", end=" ")
            score += 1
        else:
            print("\nWrong.", end=" ")
        print(explanation)
        print("Score:", score, "\n\n")

        # get next block
        category, question, answers, correct, explanation = next_block(trivia_file)

    trivia_file.close()

    print("That was the last question!")
    print("Your final score is", score)


main()  

That is most of the code associated with the program. I will be very grateful for any support available.

Nazim Kerimbekov
  • 4,712
  • 8
  • 34
  • 58
Tara
  • 11
  • 1
  • 2
    You will need to read in *all* the questions and their answers in one pass of the file, and then perhaps shuffle the questions (and their answers) and finally ask each question in turn. (see also: https://stackoverflow.com/questions/976882/shuffling-a-list-of-objects) – quamrana Apr 30 '19 at 12:37

1 Answers1

0

You can read the file and group its contents into blocks of eight. To generate unique random questions, you can use random.shuffle and then list slicing to create the groups of questions. Also, it is cleaner to use a collections.namedtuple to form the attributes of the question for use later:

import random, collections
data = [i.strip('\n') for i in open('filename.txt')]
questions = [data[i:i+8] for i in range(0, len(data), 8)]
random.shuffle(questions)
question = collections.namedtuple('question', ['category', 'question', 'answers', 'correct', 'explanation'])
final_questions = [question(*i[:2], i[2:6], *i[6:]) for i in questions]

Now, to create the groups of 10:

group_questions = [final_questions[i:i+10] for i in range(0, len(final_questions), 10)]

The result will be a list of lists containing the namedtuple objects:

[[question(category='Category', question='Question', answers=['Answer', 'Answer', 'Answer', 'Answer'], correct='Correct Answer', explanation='Explanation ')]]

To get the desired values from each namedtuple, you can lookup the attributes:

category, question = question.category, question.question

Etc.

Ajax1234
  • 69,937
  • 8
  • 61
  • 102