首页 > 解决方案 > Python中带有递归函数的if语句的逻辑

问题描述

我有以下简单的递归函数:

def draw_interval(center_length):
    if center_length > 0: 
        print('first value: {}'.format(center_length))
        draw_interval(center_length - 1)      
        print('second value: {}'.format(center_length))              

draw_interval(3)

输出是:

first value: 3
first value: 2
first value: 1
second value: 1
second value: 2
second value: 3

我的问题是为什么会这样,并且draw_interval(center_length - 1)即使在center_length > 0False 之后函数也会运行。我已经看到了一个类似的问题,但我的问题指向 Python 中递归功能和条件语句的不同角度。

标签: pythonif-statementrecursiondata-structures

解决方案


这是您的函数递归的方式:

draw_interval(3):
    center_length > 0 is true
    "first value 3"
    draw_interval(2):
        center_length > 0 is true
        "first value 2"
        draw_interval(1):
            center_length > 0 is true
            "first value 1"
            draw_interval(0):
                center_length > 0 is FALSE: no more calls to `draw_interval` are made
                execution returns to draw_interval(1)
            "second value 1"
            execution returns to draw_interval(2)
        "second value 2"
        execution returns to draw_interval(3)
    "second value 3"
    execution returns to the end of your program

它不运行之后draw_interval(center_length - 1)center_length > 0False。


推荐阅读