python - 为什么放入'if'语句时函数会自动打印
问题描述
为什么执行此代码时,我会得到“嗨”?
谢谢!
def b():
print("hi")
def c():
return True
if b() == 'hi':
print("Done")
解决方案
您将打印到控制台与返回值混淆了。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) ——它为您提供了有关如何自己修复代码并通过调试发现错误的提示。
推荐阅读
- python - 如何从数组中生成字典字典?
- php - 如何检查 VARCHAR 列是否包含字符串的子字符串?
- c++ - Unix/Linux 中卷设备的 createFile() 和 DeviceIoControl() 等效项
- kaios - 不知道如何在 KaiOS 中杀死应用程序进程
- javascript - 错误调用 API
- text - 预处理文本,以便检测到没有分隔空格(或连字符分隔)的两个单词
- java - Android在视图组内设置视图位置
- spring - Read multiple properties file in one go using Spring Boot?
- regex - 我正在尝试从文件中提取一行
- r - R-使用存储在服务器上的文件部署闪亮应用程序的问题