Тест на Python с множественным выбором: вопросы, выбранные случайным образом, ответы в произвольном порядке с использованием текстового файла и списка

Я застрял в своем задании, и мне нужна помощь в том, как заставить его делать то, что от него требуется.

Задача состоит в том, что программа представляет собой викторину с несколькими вариантами ответов, которая должна случайным образом выбирать вопрос, отображать ответы в случайном порядке и использовать список, чтобы заставить его работать. Моя проблема в том, что я вообще не могу распечатать вопросы. Я могу напечатать первую строку из списка, но она неправильно отформатирована, и я не могу заставить программу распознавать правильный ответ как правильный ответ.

Я понимаю, что код, который у меня сейчас есть, не закончен, но это все, что я мог сделать, прежде чем я застрял. Вот что у меня есть на данный момент:

qList = [
    ("Who was the first president to hold a press conference on television?", "John F. Kennedy", "Dwight D. Eisenhower", "Richard M. Nixon", "Lyndon B. Johnson"),
    ("Which president served the shortest term (dying 32 days after taking the oath of office)?", "William Henry Harrison", "Chester A. Arthur", "William Taft", "Zachary Taylor"),
    ("Who was the first president to be born in a hospital?", "Jimmy Carter", "Gerald Ford", "George H. W. Bush", "Martin Van Buren"),
    ("Who was the first president to see the Pacific Ocean?", "Ullyses S. Grant", "Franklin D. Roosevelt", "Warren G. Harding", "Theodore Roosevelt"),
    ("Which president served two non-consecutive terms?", "Grover Cleveland", "Franklin Pierce", "Millard Fillmore", "Zachary Taylor"),
    ("Who was the first president to be impeached by the House of Representatives?", "Andrew Johnson", "Bill Clinton", "Donald Trump", "John Tyler"),
    ("Which president got stuck in the White House bathtub?", "William Howard Taft", "John Quincy Adams", "Teddy Roosevelt", "Millard Fillmore"),
    ("Which president never married? (His niece served as the White House hostess in lieu of a First Lady.)", "James Buchanan", "James Polk", "James Madison", "James Monroe"),
    ("Who was the first president to speak with astronauts on the moon?", "Richard Nixon", "John F. Kennedy", "Lyndon B. Johnson", "Jimmy Carter"),
    ("Who was the only person to serve as Vice-President and President, but elected to neither office?", "Gerald Ford", "Andrew Johnson", "Grover Cleveland", "Herbert Hoover"),
]

correct = 0
incorrect = 0
score = correct + incorrect


def readData():
    try:
        datafile = open("presidential_trivia.txt",'r')
        line = datafile.readline().rstrip("\n")
        line = datafile.readline().rstrip("\n")
        datafile.close()
    except ValueError:
        print("Something went wrong. File not found.")
  
    
def AskQuestions():
    global question, answer, wrong1, wrong2, wrong3
    for question in qList:
        question = []
        idx = random.randint(0, len(qList)-1)
        while used[idx]:
            idx = random.randint(0, len(qList)-1)
            print(idx)
##    if len(qList) > 0:
##        rq = random.randint(0, len(qList)-1)
##    for question in random.randint():
##        order = qList.split()
##        questions.append(mcquestion.Question())
##        print(question.question)
##        print("These are the possible answers:")
##        randomAnswers()
        userans = input("Please answer A, B, C, or D: ")
        if userans == correct:
            correct += 1
            print("Yes! That's correct!")
        else:
            incorrect += 1
            print("Sorry, that's incorrect...")

def main():
    readData()
    begin = input("Are you ready to begin? Y to start, N to exit: ").upper()
    if begin == "Y":
        AskQuestions()
        randomAnswers()
    if begin == "N":
        print("Run the program again when you're ready! We'll be right here!")
    else:
        return main()
    




main()

И это второй файл, к которому обращается программа.

class Question:
    def __init__(self, question, correct, wrong1, wrong2, wrong3):
        self.question = question
        self.correct = correct
        self.wrong1 = wrong1
        self.wrong2 = wrong2
        self.wrong3 = wrong3

    def __init__():
        self.__order = [correct, wrong1, wrong2, wrong3]
        self.__correct_answer = "A"
    
    def randomAnswers(self):
    #This is to randomize the order of the questions and the answers then stores them
        used = [False,False,False,False]#This is needed to insure distribution
        letters = ["A","B","C","D"]
        c = random.randint(0,3)
        used[c] = True
        self.__order[c] = self.__correct
        self.__correct_answer = letters[c]
        w1 = w2 = w3 = c
        while used[w1]:
            w1 = random.randint(0,3)
        used[w1] = True
        self.__order[w1] = self.__wrong1
        while used[w2]:
            w2 = random.randint(0,3)
        used[w2] = True
        self.__order[w2] = self.__wrong2
        while used[w3]:
            w3 = random.randint(0,3)
        used[w3] = True
        self.__order[w3] = self.__wrong3

    def __str__(self):
        #According to teacher, this will print the question and randomly ordered answers
        self.randomAnswers()
        #This is how the answers will be ordered after the question is printed
        return self.__question + \
                "\n  A - " + self.__order[0] + \
                "\n  B - " + self.__order[1] + \
                "\n  C - " + self.__order[2] + \
                "\n  D - " + self.__order[3]

Буду очень признателен за обратную связь и объяснение того, что не так и как я могу это исправить. Если вам нужна дополнительная информация, дайте мне знать!


person Jessica2477    schedule 09.11.2020    source источник
comment
Вместо того, чтобы публиковать большой фрагмент кода с проблемой, скрытой внутри него, что является проблемой, которую вы в настоящее время решаете, обычно лучше попытаться изолировать проблему и поделиться только кодом, который показывает проблему, которую вы пытаетесь решить. решать. У вашего решения много проблем, из-за чего сложно сказать, почему у вас возникла текущая проблема. Вы пробовали отдельно распечатать вопросы? Как насчет отдельного ввода ответов и тестирования конкретных? Это сработало? Когда у вас есть рабочие части, объедините их в более сложный фрагмент кода.   -  person Grismar    schedule 09.11.2020
comment
что содержит ваш President_trivia.txt? Не могли бы вы опубликовать и это?   -  person Dev    schedule 09.11.2020
comment
Прости за это; Я запомню это в следующий раз. Пробовал отдельно распечатать вопросы. Я пробовал складывать вопросы и ответы в отдельные списки и соединять их вместе. Я пробовал разделить данные, но ничего не помогло. Мне сказали добавить вопросы, но это тоже не сработало. President_trivia.txt содержит ту же информацию, что и qList. Я знаю, что это избыточно, но я просто пытаюсь заставить программу работать без ввода.   -  person Jessica2477    schedule 09.11.2020
comment
Вам нужно использовать global переменную? Такие как global question, answer, wrong1, wrong2, wrong3   -  person burningalc    schedule 09.11.2020
comment
@ Jessica2477 ваш президент_trivia.txt ничего не делает в коде, к тому же в коде много опечаток, поэтому очистка будет долгой задачей. Во-первых, это ошибка имени, во-вторых, вы не импортировали случайный модуль и не начали использовать случайную библиотеку, и многое другое в будущем.   -  person Dev    schedule 09.11.2020


Ответы (1)


Итак, я изменил весь ваш код и вуаля !! Оно работает!!! Смотрите код, я написал там пояснения:

import random
import numpy as np

qlist = np.array(["Who was the first president to hold a press conference on television?", 
    "Which president served the shortest term (dying 32 days after taking the oath of office)?",
    "Who was the first president to be born in a hospital?", 
    "Who was the first president to see the Pacific Ocean?",
    "Which president served two non-consecutive terms?",
    "Who was the first president to be impeached by the House of Representatives?",
    "Which president got stuck in the White House bathtub?", "William Howard Taft",
    "Which president never married? (His niece served as the White House hostess in lieu of a First Lady.)",
    "Who was the first president to speak with astronauts on the moon?",
    "Who was the only person to serve as Vice-President and President, but elected to neither office?",
], dtype = object)

alist = np.array(["John F. Kennedy", "Dwight D. Eisenhower", "Richard M. Nixon", "Lyndon B. Johnson",
                   "William Henry Harrison", "Chester A. Arthur", "William Taft", "Zachary Taylor",
                  "Jimmy Carter", "Gerald Ford", "George H. W. Bush", "Martin Van Buren",
                   "Ullyses S. Grant", "Franklin D. Roosevelt", "Warren G. Harding", "Theodore Roosevelt",
                   "Grover Cleveland", "Franklin Pierce", "Millard Fillmore", "Zachary Taylor",
                   "Andrew Johnson", "Bill Clinton", "Donald Trump", "John Tyler",
                   "John Quincy Adams", "Teddy Roosevelt", "Millard Fillmore","John Tyler"
                   "James Buchanan", "James Polk", "James Madison", "James Monroe",
                   "Richard Nixon", "John F. Kennedy", "Lyndon B. Johnson", "Jimmy Carter",
                   "Gerald Ford", "Andrew Johnson", "Grover Cleveland", "Herbert Hoover","Jimmy Carter"], dtype = object)

#rlist array contains data for right answers:(I am not an american so pls excuse me for wrong answers, but you can change them)
rlist = np.array(["John F. Kennedy", "Chester A. Arthur", "William Taft", "Zachary Taylor", "Theodore Roosevelt", "Grover Cleveland", "Franklin Pierce",
                  "George H. W. Bush", "Martin Van Buren", "Millard Fillmore,"], dtype = object)

#print(qlist)
correct = 0
incorrect = 0
score = correct + incorrect


array_q = np.array_split(qlist, len(qlist))
array_a = np.array_split(alist, 10)

user = False
#Start_print
user_input = input("Do you want to start quizzing ?y/n ")
if user_input == "y":
    user = True

def answers_data():

    #Array to 4 options, a1 is for question 1 and so on...
    
    a1 = array_a[0]
    a2 = array_a[1]
    a3 = array_a[2]
    a4 = array_a[3]
    a5 = array_a[4]
    a6 = array_a[5]
    a7 = array_a[6]
    a8 = array_a[7]
    a9 = array_a[8]
    a10 = array_a[9]

    a = np.array_split(a1, 4)
    b = np.array_split(a2, 4)
    c = np.array_split(a3, 4)
    d = np.array_split(a4, 4)
    e = np.array_split(a5, 4)
    f = np.array_split(a6, 4)
    g = np.array_split(a7, 4)
    h = np.array_split(a8, 4)
    i = np.array_split(a9, 4)
    j = np.array_split(a10, 4)




def AskQuestions():
    right_ans = np.array_split(rlist, 10)
    score = 0
    incorrect = 0

    while user == True:
        random_no = random.randint(0, 9)
        print(str(array_q[random_no]).lstrip('[').rstrip(']'))
        print(str(array_a[random_no]).lstrip('[').rstrip(']'))
        u = input("Answer : ")

        #checking for exit
        if u == "q":
            break
        print("Thanks for playing with us..")

        #checking for answers:
        
        if u == right_ans[random_no]:
            score += 1
            print("score = %d incorrect = %d"%(score, incorrect))
        else:
            incorrect += 1
            print("score = %d incorrect = %d"%(score, incorrect))

    
            
        
                
        
       

AskQuestions()
    

Если у вас нет библиотеки numpy, вы можете перейти в cmd или bash и ввести:

pip install numpy

Это должно сработать. :)

person Dev    schedule 09.11.2020