我刚开始学习 Python,我一直在乱敲不同的代码来练习学习,我做了这段代码:
import math
def lol():
print (math.cos(math.pi))
print ("I hope this works")
def print_twice(bruce):
print bruce
print bruce
print_twice(lol())
当我运行它时,我的输出是:
-1.0
I hope this works
None
None
为什么它没有打印函数 lol() 两次?
请您参考如下方法:
您的代码 print_twice(lol())说要执行 lol()并将其返回值传递给 print_twice() .由于您没有为 lol() 指定返回值, 它返回 None .因此, lol() 在执行时打印一次,并且 print 都打印一次。 print_twice() 中的陈述打印 None 的传递值.
这就是你想要的:
def lol():
print (math.cos(math.pi))
print ("I hope this works")
def print_twice(bruce):
bruce()
bruce()
print_twice(lol)
而不是传递 lol() 的返回值 ,我们现在传递函数 lol ,然后我们在 print_twice() 中执行两次.
