首先,我想说的是继续学习 Python 并通过教程进行改进。
我将在代码中的 cmets 中尽可能好地解释我编写的重构代码,以便您对这里发生的事情有所了解。如果您还有疑问,请随时在 cmets 中问我。
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