【问题标题】:For loop only executes 1 time, though given a range of 5For 循环仅执行 1 次,但范围为 5
【发布时间】:2012-04-15 17:37:13
【问题描述】:

我有以下代码:

def input_scores():
scores = []
y = 1
for num in range(5):
    score = int(input(print('Please enter your score for test %d: ' %y)))

    while score < 0 or score > 100:
        print ('Error --- all test scores must be between 0 and 100 points')
        score = int(input('Please try again: '))
    scores.append(score)
    y += 1
    return scores   

当我运行它时,输出如下:

Please enter your score for test 1: 
None

然后我将在无旁边输入测试分数,例如 95 然后它会运行程序的其余部分,而不提示我将下一个测试分数添加到分数列表中。我真的很好奇为什么会这样

提前感谢您抽出宝贵时间提供帮助

真诚地, ~达斯汀

【问题讨论】:

  • 请注意:input 函数调用是错误的,您不需要其中的 print 函数。它应该只是字符串。这就是为什么它在提示后打印None
  • 你的函数需要缩进(第一行之后的所有内容)
  • 另一个快速说明:我从您的代码中推断出您使用的是 Python 3,而不是 Python 2 - 将您的问题标记为 Python-3.x 很重要,这样我们就不会感到困惑。除非您另有说明,否则我们通常假定您使用的是 Python 2,而我们需要给出的建议可能会大不相同。
  • 你也许可以摆脱y变量。如果你需要它,你可以使用len(scores) + 1

标签: python for-loop python-3.x range


【解决方案1】:

你从循环内部返回。将return scores 向左缩进一格。

【讨论】:

    【解决方案2】:

    您的 return 语句缩进太多,导致函数在第一次迭代时返回。它需要在 for 块之外。此代码有效:

    def input_scores():
        scores = []
        y = 1
        for num in range(5):
            score = int(input('Please enter your score for test %d: ' %y))
            while score < 0 or score > 100:
                print ('Error --- all test scores must be between 0 and 100 points')
                score = int(input('Please try again: '))
            scores.append(score)
            y += 1
        return scores
    

    【讨论】:

      【解决方案3】:

      您的代码缩进看起来很奇怪。看起来 return 语句在 for 循环的范围内。因此,在第一次迭代之后,return 语句将您完全带出函数。

      【讨论】:

      • 我明白了。似乎是一个愚蠢的错误,但我们都犯了,对吧,哈哈?谢谢
      【解决方案4】:

      您在每次循环迭代结束时returning scores(换句话说,在第一次循环迭代完成后,您返回所有分数,从而退出函数和循环)。

      将您的代码更改为:

      for num in range(5):
          # ...
      return scores    # Note the indentation is one tab less than the loop's contents
      

      【讨论】:

        【解决方案5】:

        其他人已正确指出您的 return 语句的缩进导致了问题。此外,您可能想像这样尝试它,使用 len(scores) 来控制循环,正如@max 建议的那样:

        def input_scores(num_tests=5, max=100, min=0):
            scores = []
            while len(scores) < num_tests:
                score = int(input('Please enter your score for test {0}: '.format(len(scores)+1)))
                if score < min or score > max: 
                    print ('Error --- all test scores must be between 0 and 100 points.')
                else:
                    scores.append(score)
            return scores
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-06-15
          • 2011-10-21
          • 2018-09-08
          相关资源
          最近更新 更多