【发布时间】:2020-09-28 18:55:19
【问题描述】:
对于学校练习,我必须用 Python 编写一个程序来回答下一个问题。有一个测验,挑战者需要回答特定数量的问题(n),并且“破解”需要说明挑战者是否选择了正确的答案。我们需要计算挑战者的正确答案数量和破解者的正确答案数量。输入包括 n(= 问题数量)、正确(= 正确答案:A、B 或 C)、挑战者(= 挑战者的答案:A、B 或 C)和破解(= 破解的答案:正确或错误)。 这是我已经编写的代码:
# Input
n = int(input()) # Number of questions
correct = input() # The correct answer to the question
challenger = input() # The answer from the challenger
crack = input() # The answer from the crack; Is the answer of the challenger correct or wrong?
m = n - 1
a = 0 # Points for the challenger
b = 0 # Points for the crack
for i in range(m):
if correct == challenger and crack == "correct":
a += 1
b += 1
elif correct == challenger and crack == "wrong":
a += 1
elif correct != challenger and crack != "correct":
b += 1
else:
pass
correct = input()
challenger = input()
crack = input()
if a > b:
print("challenger wins {} points against {}".format(a, b))
elif a == b:
print("ex aequo: both contestants score {} points".format(a))
else:
print("crack wins {} points against {}".format(b, a))
我在 for 循环中有问题。例如,如果有 5 个问题(n = 5),则前 4 个输入有效,挑战者和破解者的分数应该算得上。最后一系列输入进入循环(我已经用 Python Tutor 进行了检查),但结果没有添加到挑战者/破解的点。如何修复此错误?
此处显示了一个输入示例:
5
A
A
correct
B
B
wrong
A
C
correct
C
C
correct
C
C
correct
【问题讨论】:
-
您明确删除了最后一个问题:
m = n - 1。 -
考虑在
input()方法中添加一些文本会有所帮助,例如correct = input("Please enter the correct answer") -
当我使用 n 并且有例如 5 个问题时,由于某些我不明白的原因,程序想要第六个输入,这就是我使用 m = n - 1 的原因。但是输入在 for 循环之后(如下面的答案所述),我确实需要使用 n (当然这更符合逻辑!)。
标签: python python-3.x for-loop