如果将“i”定义为整数,它如何知道问题==答案?

2024-04-19 01:52:50 发布

您现在位置:Python中文网/ 问答频道 /正文

这个程序很实用,我的问题更多是出于好奇和教育的考虑。如果我将“I”定义为“answers”长度范围内的整数,它如何知道用户的输入是否等于原始字符串?你知道吗

示例: (#第一次迭代)A、B、C或D?(我回答)B (#answers[i]==1,但程序知道它也等于B,并验证第一个输入是否正确。如果“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)

Tags: oftoaddresponselistanswersquestionsquestion
1条回答
网友
1楼 · 发布于 2024-04-19 01:52:50

answers[i]意味着您在answers数组中查找第i个元素,得到存储在那里的值(在您的例子中是一个字符串)。你知道吗

如果您在第一次迭代中,i将为0。你知道吗

answers[0]然后将给您存储在answers中索引0处的值,即字符串'B'

如果用户输入B,您的比较:

if question == answers[i]:

与相同

if 'B' == 'B':

相关问题 更多 >