首页 > 解决方案 > 为什么放入'if'语句时函数会自动打印

问题描述

为什么执行此代码时,我会得到“嗨”?

谢谢!

def b():
    print("hi")
def c():
    return True
if b() == 'hi':
    print("Done")

标签: pythonfunctionif-statement

解决方案


您将打印到控制台与返回值混淆了。None如果您不从中返回任何内容,则您的函数将隐式返回,因此它永远不等于'hi'. 您b()确实打印 - 并且不返回它'hi'

def b():
    print("hi")  # maybe uncomment it if you do not want to print it here
    return "hi"  # fix like this (which makes not much sense but well :o)

def c():
    return True
if b() == 'hi':
    print("Done")

你可以像这样测试它:

def test():
    pass

print(test())

输出:

None

进一步阅读:


还有一件更重要的事情要阅读:如何调试小程序(#1) ——它为您提供了有关如何自己修复代码并通过调试发现错误的提示。


推荐阅读