Как сделать так, чтобы тест отображал ответы учеников и показывал правильные ответы с оценкой? - PullRequest
0 голосов
/ 26 апреля 2019

Так что я в основном пытаюсь повторить это изображение, как показано на рисунке. У меня проблема в том, что когда я запускаю программу, она в основном говорит мне, что я не могу ее запустить. Я не уверен, что где-то в моем коде есть ошибки. Я получаю сообщение об ошибке всякий раз, когда запускаю его из-за синтаксической ошибки в части «else:». enter image description here

def main():
examAnswers = ['A', 'C', 'A', 'A', 'D', 'B', 'C', 'A', 'C', 'B']
countCorrect = 0
countWrong = 0
studentAnswers = getStudentAnswers()

for i in range(10):
 if examAnswers[i] == studentAnswers[i]:
    print("Congratulations!", countCorrect + 1)
    else:
        print("Wrong!", countWrong + 1)


listOfAnswers = []
for qnum in range(10):
print("Enter answer to question ", qnum+1, ":", sep="", end="")
listofAnswers.append(input())
return listOfAnswers

main()

1 Ответ

1 голос
/ 26 апреля 2019

Для начала я бы сказал, продолжайте изучать Python и изучать учебные материалы для улучшения.
Я поясню измененный код, который я написал, как можно лучше в комментариях к коду, чтобы вы могли понять, что здесь происходит. Если у вас все еще есть сомнения, не стесняйтесь спрашивать меня в комментариях.

Логика getStudentAnswers определена в функции, как показано ниже, и я вызываю эту функцию в основном фрагменте кода, который начинается с переменной examAnswers. Отступ играет большую роль в python, поэтому сначала выполняется код без отступа, и он вызывает функцию getStudentAnswers.

#Function to get the answers of students
def getStudentAnswers():

    listOfAnswers = []

    #Run a for loop 10 times
    for qNum in range(10):

        #Get the answer from the user
        print("Enter answer to question ", qNum + 1, ": ", sep="", end="")
        answer = input()

        #Append the answer to the list
        listOfAnswers.append(answer)

    #Return the final list of answers
    return listOfAnswers

#List of valid exam answers
examAnswers = ['A', 'C', 'A', 'A', 'D', 'B', 'C', 'A', 'C', 'B']

#Variable to hold the count of correct and wrong answers
countCorrect = 0
countWrong = 0

#Get all the answers from the students
studentAnswers = getStudentAnswers()

#Run a for loop 10 times
for i in range(10):

    #If exam answer matches student answer, print it and increment countCorrect
    if examAnswers[i] == studentAnswers[i]:
        countCorrect+=1
        print('Question',i+1,'is correct!')

    # If exam answer does not match student answer, print it and increment countWrong
    else:
        print('Question',i+1,'is WRONG!')
        countWrong+=1

#Calculate number of missedQuestions and grade and print it
missedQuestions = 10 - countCorrect
grade = 10*countCorrect

print('You missed',missedQuestions,'questions.')
print('You grade is:',grade)

Как только вы запустите код, вы должны получить требуемый вывод, как показано ниже.

Enter answer to question 1: A
Enter answer to question 2: B
Enter answer to question 3: C
Enter answer to question 4: D
Enter answer to question 5: A
Enter answer to question 6: B
Enter answer to question 7: C
Enter answer to question 8: D
Enter answer to question 9: A
Enter answer to question 10: A
Question 1 is correct!
Question 2 is WRONG!
Question 3 is WRONG!
Question 4 is WRONG!
Question 5 is WRONG!
Question 6 is correct!
Question 7 is correct!
Question 8 is WRONG!
Question 9 is WRONG!
Question 10 is WRONG!
You missed 7 questions.
You grade is: 30
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...