所以我基本上是在尝试复制该图像,如图所示。我的问题是,每当我运行该程序时,它基本上会告诉我无法运行它。我不确定我的代码中是否存在错误。每当我运行它时,由于“ else:”部分的语法错误,都会出现错误。
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()
答案 0 :(得分:1)
首先,我要说的是继续学习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