【问题标题】:Why should this be a while statement and not an if statement?为什么这应该是 while 语句而不是 if 语句?
【发布时间】:2017-05-14 06:30:30
【问题描述】:

为班级做了一个测试......他们提供了一个样本测试。其中一个问题给出了以下代码,该代码计算列表中项目的平均值,然后他们要求我们找出所有错误:

# brightness levels –maximum is 100
shape_brightness = [15,92,38,42] 
item_no = 0
total = 0
if (item_no < len(shape_brightness):
  total = shape_brightness[item_no]
  item_no = item_no + 1
  average = total / item_no
print(“The average brightness level is “+str(averge))

但是,在解决方案中,他们说最大的错误是它实际上应该是一个 while 语句 .. 我不明白为什么?有什么解释吗??

【问题讨论】:

    标签: loops if-statement while-loop statements


    【解决方案1】:

    您需要遍历所有元素来计算平均值。 if 语句只访问这个数组的第一个元素。

    当你的代码访问shape_brightness[item_no]时,item_no是索引,所以它是0,shape_brightness[item_no]只是数字15。为了在你的平均计算中包括shape_brightness的所有其他值,您也想访问它们,因此您可以通过使用循环将索引 item_no 增加与要访问的元素数量一样多。

    while 循环是遍历所有元素的一种方法,将“if”更改为“while”将是对这段代码的最快修正,但带有额外更改的 for 循环也可以工作。例如

    for item in range(len(shape_brightness)):
        execute
    

    在这种情况下 item_no 计数器变得不必要。

    【讨论】:

      【解决方案2】:

      简单:

      因为你需要迭代一个数组。这意味着:您需要某种形式的循环!

      而且 if 语句没有此处需要的 重复 部分!

      【讨论】:

      • 哦,这更有意义,但我认为我们只需要计算一次平均值?我们到底想循环什么??
      • 您需要对数组中的所有元素进行一些处理!如果不循环阅读它们,你如何做到这一点?!
      【解决方案3】:

      您需要使用while 循环,因为用于计算平均值的总和和数量。您需要重复添加形状亮度的值,直到添加完所有值。目前,您正在使用 if 块,它只考虑 shape_brightness 数组的第一个值。你需要把

          total = shape_brightness[item_no]
       item_no = item_no + 1
      

      while循环内

      while(item_no < len(shape_brightness))
      

      【讨论】: