V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
xshell
V2EX  ›  Python

一个 python 很简单的问,但是和书上运行的结果不一样,求科普

  •  
  •   xshell · 2015-10-15 10:51:20 +08:00 · 2082 次点击
    这是一个创建于 3117 天前的主题,其中的信息可能已经有所发展或是发生改变。
    x = 0
    for i in [1,2,3,4,5]:
    if x == i:
    continue
    x += i
    print "x:", x

    我在 python2.7 下运行 x 的值是 5 ,但是书上说 x 的结果是 12~~~

    这是什么问题呢·,··

    += 这个符号在 python2 的运算符中没有找到
    bl2fu
        1
    bl2fu  
       2015-10-15 11:14:09 +08:00
    逻辑上是 12
    anjouslava
        2
    anjouslava  
       2015-10-15 11:48:33 +08:00
    12 ,估计你是缩进错了, x+= i 放在 for 循环之外了
    x = 0
    for i in [1,2,3,4,5]:
    if x == i:
    continue
    x += i #注意这里的缩进
    print "x:", x
    anjouslava
        3
    anjouslava  
       2015-10-15 11:52:19 +08:00
    在线运行结果 http://codepad.org/4brvhGvb
    TimePPT
        4
    TimePPT  
       2015-10-15 11:54:23 +08:00   ❤️ 1
    请购买游标卡尺 :)
    xshell
        5
    xshell  
    OP
       2015-10-15 14:14:14 +08:00
    @anjouslava @bl2fu @TimePPT
    谢谢三位,果然是缩进的问题·
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   872 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 21:44 · PVG 05:44 · LAX 14:44 · JFK 17:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.