推荐学习书目
› 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
mintLeaf
V2EX  ›  Python

这个递归的返回值为什么是 0,1(代码格式已修改)

  •  
  •   mintLeaf · Jun 8, 2016 · 4040 views
    This topic created in 3792 days ago, the information mentioned may be changed or developed.

    def a(i):
      if i==0:
        return
       i = i - 1
      a(i)
      print i

    a(2)

    5 replies  •  2016-06-08 22:36:04 +08:00
    wjfz
        1
    wjfz  
       Jun 8, 2016
    你以为是 1 , 0 ?
    mornlight
        2
    mornlight  
       Jun 8, 2016   ❤️ 1
    你的疑惑在哪呢?
    里面
    a(i)
    print i
    这两句,要先等 a(i)执行完才会 print ,最底层的递归调用先 print 结果,最底层的调用是 a(0),没有输出,再往上一层是 a(1),输出 0 ,再往上是 a(2),输出 1
    SuperFashi
        3
    SuperFashi  
       Jun 8, 2016 via Android   ❤️ 1
    你高中的程序框图是不是没认真学啊……
    进入 a(i=2)
    判断==(否)
    i=1
    进入 a(i=1)
    {
    判断==(否)
    i=0
    进入 a(i=0)
    {
    判断==(是)
    返回
    }
    打印 i (也就是 0)
    返回
    }
    打印 i (也就是 1)
    返回
    mintLeaf
        4
    mintLeaf  
    OP
       Jun 8, 2016
    多谢大家,明白了
    iamxi
        5
    iamxi  
       Jun 8, 2016
    print i 这句在 a(i)之后,所以优先执行 a(i)内的 print i 。
    而且 print i 这句在 a(i)之后,不算尾递归。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2959 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 12:33 · PVG 20:33 · LAX 05:33 · JFK 08:33
    ♥ Do have faith in what you're doing.