该程序具有功能,我的问题更多是出于好奇和教育的缘故。如果我已将“ i”定义为“答案”长度范围内的整数,那么如何知道用户的输入是否等于原始字符串?
示例: (#首次迭代)A,B,C或D? (#我回答)B (#answers [i] == 1,但是程序知道它也等于B并验证第一个输入是否正确。如果将“ i”定义为整数,它如何知道第一个答案[i]是B?
# List of question answers
answers = ['B', 'D', 'A', 'A', 'C', 'A', 'B', 'A', 'C', 'D']
# List of user responses
response = []
# List of questions answered correctly
correct = []
# Number correctly answered
numCor = 0
# Number incorrectly answered
numIn = 0
# For every question answer, add user-reponse to response list
for i in range(len(answers)):
question = input('A, B, C, or D: ')
response.append(question)
# If the user-response is equal to the question answer /
# add 1 to correctly answered and add question-number to correct list
if question == answers[i]:
numCor += 1
correct.append(i + 1)
# If user-response does not match question answer /
# add 1 to incorrectly answered
else:
numIn += 1
# Print correctly/incorrectly answered /
# and question-numbers answered correctly
print('You got', numCor, 'questions correct.')
print('You got', numIn, 'questions incorrect.')
print('Correct Questions:', correct)
答案 0 :(得分:2)
answers[i]
表示您在answers
数组中查找第i个元素,并获得存储在其中的值(以您的情况为字符串)。
如果您是第一次迭代,则i
将为0。
answers[0]
将为您提供存储在answers
的索引0中的值,该值是字符串'B'
如果用户输入B
,则您的比较:
if question == answers[i]:
与
相同if 'B' == 'B':