[Python] Quiz Program using a Text File

Discussão em 'Python' iniciado por Stack, Março 3, 2025.

  1. Stack

    Stack Membro Participativo

    Am trying to create a quiz program in Python where the questions are stored in one txt file with the answers in another. The questions are set out in the text file as follows:

    Which one of these is a percussion instrument?
    A. Trumpet
    B. Euphonium
    C. Viola
    D. Glockenspiel


    The program pulls the questions out in random order and keeps score of the number of right answers.

    I know how to open files, read from them and display the contents of the file on the screen, I even know now how to randomise the info in the file. However, as there are multiple lines involved AND another file to get the answer from, I have no idea where to start. I would really appreciate any help you could offer me. Feel free to ask questions if you need to clarify anything.

    EDIT: Ok, I have decided to change my idea a little, which might make it easier. Using a CSV file might be the better option. Here is what I have so far.

    def Trivia():
    score=0
    myFile = open("farming.csv","r") # opens the CSV file and stores it in the array myFile
    players = myFile.readlines() # reads the lines of the CSV file into the variable players
    questionno=1
    while questionno < 6:

    for p in players:
    data = p.split(",") #splits each cell of the CSV file into its parts
    questions = data[0]
    answera = data[1]
    answerb = data[2]
    answerc = data[3]
    CorrectAnswer = data[4]
    print("Question #",questionno)
    print(questions) #prints the question and the 3 answers
    time.sleep(0.5)
    print(answera)
    time.sleep(0.5)
    print(answerb)
    time.sleep(0.5)
    print(answerc)
    time.sleep(0.5)
    answer = input("Answer? ") #asks the user for their answer
    time.sleep(1)
    print(".")
    time.sleep(1)
    print(".")
    time.sleep(1)
    print(".")

    if answer == CorrectAnswer: #checks if the answer is correct and prints approptiate responses
    print("That is the correct answer")
    score=score+1
    time.sleep(1)
    else:
    print("That is not the correct answer")
    time.sleep(1)
    print("Your current score is", score)
    print("")
    questionno = questionno+1

    myFile.close()


    My problem now is that I don't know how to get to the next question in the quiz. Using this format it keeps asking the same question. Any idea?

    Thanks.

    Continue reading...

Compartilhe esta Página