Для начала я бы сказал, продолжайте изучать 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