Я застрял в своем задании, и мне нужна помощь в том, как заставить его делать то, что от него требуется.
Задача состоит в том, что программа представляет собой викторину с несколькими вариантами ответов, которая должна случайным образом выбирать вопрос, отображать ответы в случайном порядке и использовать список, чтобы заставить его работать. Моя проблема в том, что я вообще не могу распечатать вопросы. Я могу напечатать первую строку из списка, но она неправильно отформатирована, и я не могу заставить программу распознавать правильный ответ как правильный ответ.
Я понимаю, что код, который у меня сейчас есть, не закончен, но это все, что я мог сделать, прежде чем я застрял. Вот что у меня есть на данный момент:
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]
Буду очень признателен за обратную связь и объяснение того, что не так и как я могу это исправить. Если вам нужна дополнительная информация, дайте мне знать!
global
переменную? Такие какglobal question, answer, wrong1, wrong2, wrong3
- person burningalc   schedule 09.11.2020