0
votes

I'm stuck on my assignment and I'd like some help on how I can make it do what it's supposed to.

The task is the program is a multiple choice quiz that needs to randomly select a question, display the answers in random order, and use a list to get it working. My problems are I can't get the questions to print at all. I can get the first line printed from the list, but it is incorrectly formatted and I can't get the program to recognize the correct answer as the correct answer.

The code I currently have is not finished, I understand, but it's as far as I could make it before I got stuck. Here is what I have so far:

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()

And this is the second file that the program calls to.

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]

I'd really appreciate feedback and an explanation of what's wrong and how I can fix it. If you need any more info please let me know!

1
Instead of posting a large piece of code with a problem hidden inside of it, which happens to be the problem you're currently solving, it's generally better to try and isolate the problem and only share code that shows the problem you're trying to solve. Your solution has many issues, making it hard to say why you have your current problem. Have you tried separately printing the questions? How about separately entering answers and testing specific ones? Did that work? Once you have working pieces, put those together in a more complicated piece of code. - Grismar
what does your "president_trivia.txt" contain ? Could you post that as well? - Dev
Sorry about that; I'll keep that in mind for next time. I've tried separately printing the questions. I've tried putting the questions and answers in separate lists and connecting them together. I've tried splitting the data, and nothing has worked. I was told to append the questions, but that hasn't worked either. The "president_trivia.txt" contains the exact same information as the qList. I know it's redundant, but I'm just trying to get the program to work past the input. - Jessica2477
Do you have to use global variable? Such as global question, answer, wrong1, wrong2, wrong3 - burningalc
@Jessica2477 your president_trivia.txt does nothing in the code , additionaly the code has many typos, so cleaning would be a long task. Firstly there is a name error, secondly you havent imported the random module and started using random library, and much more to come. - Dev

1 Answers

0
votes

So I modified your whole code and voila !! It works!!! See the code , I have written explanations there :

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()
    

In case you dont have numpy library, you can go to cmd or bash and type:

pip install numpy

That should work. :)