【问题标题】:My code doesn't calculate the last values in a loop [closed]我的代码不计算循环中的最后一个值[关闭]
【发布时间】: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


【解决方案1】:

m = n-1 设置的问题比用户选择的少一个,直接使用n。还要在循环开始的时候询问其他3个元素,这样可以避免代码重复,最后一个input会在最后空着用

n = int(input("Number of questions"))
a = 0
b = 0

for i in range(n):
    correct = input("Correct answer: ")
    challenger = input("Challenger answer: ")
    crack = input("Crack answer")

    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

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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-21
    • 2018-01-29
    • 1970-01-01
    • 2022-12-30
    • 1970-01-01
    • 2021-03-16
    相关资源
    最近更新 更多