多项选择题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",("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","Lyndon B. Johnson","Jimmy Carter"),("Who was the only person to serve as Vice-President and President,but elected to neither office?","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,wrong3):
        self.question = question
        self.correct = correct
        self.wrong1 = wrong1
        self.wrong2 = wrong2
        self.wrong3 = wrong3

    def __init__():
        self.__order = [correct,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]#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]

我非常感谢您提供反馈意见,并解释了问题所在以及解决方法。如果您需要更多信息,请告诉我!

解决方法

所以我修改了整个代码,瞧!有用!!!看代码,我在那里写了解释:

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","Andrew Johnson","Bill Clinton","Donald Trump","John Tyler","John Quincy Adams","Teddy Roosevelt","John Tyler"
                   "James Buchanan","James Polk","James Madison","James Monroe","Richard Nixon","John F. Kennedy","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","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

应该可以。 :)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...