【问题标题】:using xrange output not expected不使用 xrange 输出
【发布时间】:2017-08-09 08:32:36
【问题描述】:
s = 0

for s in xrange(0, 100):
    print "s before", s
    if s % 10 == 0:
        s += 10
    print "s after", s

s = 0

while s < 100:
    print "s before", s
    if s % 10 == 0:
        s += 10
    s += 1
    print "s after", s

如上图所示,为什么这 2 个循环做类似的事情,一个使用 xrange 而另一个使用 while-loop 却给了我完全不同的输出?

【问题讨论】:

  • 这些是不同的循环!
  • 因为fors 设置为可迭代对象,并且将s 设置为循环中的其他内容不会更改可迭代对象。
  • 你本质上是在问为什么s = first_thing 然后s = second_thing 没有改变first_thing
  • 是的,非常感谢。知道了

标签: python python-2.7 xrange


【解决方案1】:

第一个循环中的s 被来自xrange(0, 100) 的值覆盖,而在第二个for 循环中,您手动 初始化变量s=0,然后用s += 10 递增它.所以,这正是预期的行为。

您需要查看 python 中的变量范围。检查此讨论:Short Description of the Scoping Rules?

【讨论】:

  • 非常感谢您的回答和分享的链接。
  • 非常感谢,抱歉回复晚了。最重要的是,你解决了我的问题。
猜你喜欢
  • 2018-04-01
  • 1970-01-01
  • 2016-01-31
  • 2016-02-18
  • 1970-01-01
  • 1970-01-01
  • 2014-05-23
  • 2012-06-16
  • 1970-01-01
相关资源
最近更新 更多