首页 > 解决方案 > Python函数在return语句后召回自己?

问题描述

这个问题比较学术。我在python中遇到了以下行为:

此代码:

def dosth():
   print("new")
   for n in range(0,10):
       return False
dosth()

实际上给了我 10 张照片而不是一张。那么函数在return语句之后是否因为没有break而递归调用自己呢?如果我在 return 语句之前休息一下,我仍然会得到 2 次打印,而不是只有 1 次。有人可以解释这种行为吗

标签: pythonpython-3.xreturn

解决方案


I only see one new printed.

It also appears that you're a missing a colon : at the end of your loop for n in range(0,10).

def dosth():
   print("new")
   for n in range(0,10):
       return False
dosth()
# prints 'new' once...

推荐阅读