python - 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 > 0
False 之后函数也会运行。我已经看到了一个类似的问题,但我的问题指向 Python 中递归功能和条件语句的不同角度。
解决方案
这是您的函数递归的方式:
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 > 0
False。
推荐阅读
- c# - 是否可以在 DataTable.Compute 表达式中使用局部变量作为过滤器?
- c# - 无法使用图形 API 发送邮件
- javascript - 按顺序提取文本标签 - 如何做到这一点?
- python-3.x - 如何编辑我的代码以使“下一步”按钮指向同一窗口中的空白页面?(不是新窗口)
- javascript - 未捕获的类型错误:无法在 Object.addListitem、ctrlAddItem、HTMLDocument 处读取 null- 的属性“insertAdjacentHTML”
- python - 无法将数据帧的 RPYC netref 转换为局部变量
- java - 将基于游标的节点遍历限制为传出边
- angular - 将角度路由映射到键是路径属性的类型
- sorting - 为什么 sort -u 或 uniq 不删除串联文本文件中的重复项?
- jira - Jira - 按用户限制可用状态