lundi 3 août 2020

Generating quiz questions randomly from a file in Python

I'm just practising in Python and have an issue, I'm trying to generate a quiz from a text file which will ask a random question from the file.

It is supposed to read the question then list the answers, separating them with the commas in the file which did work before trying to randomise.

At the moment it is just reading the first character of the line then display error "list index out of range" when trying to print "detail[1]". For example if it picks line 3 in the text file, will read "C" then when inputting will come up with the error.

Text file is below:

A,What is 1+1?,1,2,3,4,b,
B,What is 2+2?,1,2,3,4,d,
C,What is 3+3?,2,4,6,8,c,
D,What is 4+4?,4,8,12,18,b,
E,What is 6+6?,18,12,10,9,b,
F,What is 1+2?,1,2,3,4,c,
G,What is 5+5?,5,6,7,10,d,
H,What is 2*2?,2,4,6,8,b, 

Code is below:

import random
class question:
def rand_line(fname):
        lines = open(fname).read().splitlines()
        return random.choice(lines)

file = rand_line("questions.txt")

for line in file:
    detail = line.split(",")
    print(detail[0])
    input()
    print(detail[1])
    print("a: ", detail[2])
    print("b: ", detail[3])
    print("c: ", detail[4])
    print("d: ", detail[5])
    print("Select A, B, C or D: ")
    select = input()
    if select == detail[6]:
        print("correct!")
    else:
        print("incorrect")



Aucun commentaire:

Enregistrer un commentaire