python - 如果“i”被定义为一个整数,它如何知道 question==answers 与否?
问题描述
这个程序是功能性的,我的问题更多是出于好奇和教育的目的。如果我将“i”定义为“answers”长度范围内的整数,它如何知道用户的输入是否等于原始字符串?
示例:(#first 迭代)A、B、C 还是 D?(#I answer) B (#answers[i]==1, 但程序知道它也等于 B 并验证第一个输入是否正确。如果 "i"' 它如何知道第一个答案 [i] 是 B s 被定义为整数?
# 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)
解决方案
answers[i]
意味着您查找answers
数组中的第 i 个元素,并获得存储在那里的值(在您的情况下为字符串)。
如果您在第一次迭代中, i
将为 0。
answers[0]
然后将为您提供存储在索引 0 in 的值answers
,即字符串'B'
如果用户输入B
,您的比较:
if question == answers[i]:
是相同的
if 'B' == 'B':
推荐阅读
- flutter - 如何验证有 5 个 textfieldfom 小部件的表单的 textfieldfom 小部件,一个一个地颤动
- powershell - Powershell在退出do-until循环后提前终止
- jquery - 未捕获的类型错误:无法读取未定义的属性 XXX
- sql - SQL:如何以 30 秒为间隔进行分组并标记该分组中的最大时间?
- java - Spring kafka:无法将消息发送到通道有效负载不能为空
- google-cloud-platform - 将参数传递给 GCMLE 预测图
- java - 当类由可变属性组成时如何确保类的不变性
- regex - 正则表达式在具有反应形式的 Angular 2+ 管道内失败
- google-sheets - 如何使用 Google 表格自定义功能来检测是否添加了行?
- r - 是否在 r 中启动包,使用第一个返回(结果)作为观察数据来计算置信区间