You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中两个void函数调用为何仅输出一个None?

原因解释

Python中无显式return语句的函数默认返回None,但函数返回值不会自动输出到控制台,只有主动对返回值做打印等输出操作时,None才会显示。

代码执行流程拆解

你的测试代码如下:

def x():
    def y():
        print('hi there this is y function')
    y()
    print('this is function x')

print(x())

实际执行顺序和输出逻辑:

  1. 调用y()时,先进入y函数内部执行print('hi there this is y function'),控制台输出第一行:hi there this is y function
  2. y函数执行完毕返回None,但这行只是单独调用函数,没有把返回值传入print,也没有其他输出操作,这个None不会被打印
  3. 继续执行x函数内的print('this is function x'),控制台输出第二行:this is function x
  4. x函数本身没有显式return,执行完毕返回None
  5. 最外层的print(x())接收到x的返回值None并打印,控制台输出第三行:None

这就是实际运行只出现一个None的原因。

如何得到你预期的输出

如果想要打印y函数返回的None,只需要主动把y的调用结果传入print即可,修改后代码:

def x():
    def y():
        print('hi there this is y function')
    print(y()) # 主动打印y的返回值
    print('this is function x')

print(x())

运行后就会得到你预期的四行输出:

hi there this is y function
None
this is function x
None

内容的提问来源于stack exchange,提问作者Shiva Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 23:54:21