【问题标题】:Variable bounding reset可变边界重置
【发布时间】:2015-12-07 10:53:39
【问题描述】:

所以学习编码...有人可以解释为什么每次循环计数都会重置为 0 吗?当您退出所有数据重置时,所有循环都会发生这种情况吗?如果是这样,是否有一个经验法则可以帮助您确定变量的边界何时更改或保持不变(在循环中还是在循环中?

iteration = 0
while iteration < 5:
    count = 0
    for letter in "hello, world":
        count += 1
    print "Iteration " + str(iteration) + "; count is: " + str(count)
    iteration += 1

【问题讨论】:

  • 你应该指出你期望的输出。
  • 我预计计数结果为 60。

标签: python loops variables while-loop


【解决方案1】:

count 每次通过循环都会重置为 0,因为将其设置为零的语句在循环内部。把while前移上去,改一下缩进就好了。

【讨论】:

  • 这正是我的问题,循环内的所有内容基本上都重置为您设置的任何内容吗?
  • @MJ49 这一切都是按顺序发生的。当您从循环顶部重新开始时,循环中的所有语句都会依次执行。如果其中一个语句将变量设置为特定值,那么随着执行的进行,这就是它的值。
【解决方案2】:

每个循环的计数都将重置为0,因为在while 之后的第一行,您将其分配为零:count = 0

【讨论】:

    【解决方案3】:

    在您将 count 重新分配给 0的每个循环中,您必须将计数排除在循环之外

    你的代码应该是这样的

    iteration = 0
    count = 0
    while iteration < 5:
        for letter in "hello, world":
            count += 1
        print "Iteration " + str(iteration) + "; count is: " + str(count)
        iteration += 1
    

    【讨论】:

      【解决方案4】:

      while 循环没有单独的范围(或命名空间),其中定义的元素不会在 while 循环的范围结束时丢失。展示这一点的示例 -

      >>> i
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      NameError: name 'i' is not defined
      >>> x = 0
      >>> while  x < 5:
      ...     x += 1
      ...     i = 12
      ...
      >>> i
      12
      

      在您的代码中,您是在每次迭代开始时重置计数的人 -

      count = 0
      

      如果您不想重置计数,则应将该行移至 while 循环之前。


      即使使用 for 循环,它也是一样的。另外,请注意,即使 for 循环中的计数器变量也是在周围的命名空间/范围内创建的。示例 -

      >>> y
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      NameError: name 'y' is not defined
      >>> for y in range(10):
      ...     pass
      ...
      >>> y
      9 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-09
        • 2019-06-14
        • 1970-01-01
        • 2014-04-28
        • 2017-06-12
        • 2014-05-14
        • 1970-01-01
        • 2017-09-27
        相关资源
        最近更新 更多