2013-01-15 128 views
1

我刚开始学习Python和我刚刚被搞乱各地的实践中学习打字不同的代码,和我做了这个代码: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()?

回答

7

您的代码print_twice(lol())说要执行lol()并将其返回值传递到print_twice()。由于您没有为lol()指定返回值,因此它返回None。因此,lol()在执行时会被打印一次,并且print_twice()打印中的print语句都会传递值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()执行两次。

+0

我应该如何改变它,所以它会打印两次?而不是返回无无。是否因为函数在print_twice(lol())中第一次被调用时会终止? –

+0

在上面编辑了更正确的版本。 –

2

您应该注意,打印与返回不同。

当你调用print_twice(lol())它会先调用lol(),它将打印-1.0I hope this works将返回None,那么它将继续调用print_twice(None)它将调用print None两次。

+0

我怎么能改变它,所以它会打印两次?而不是返回无无。是否因为函数在print_twice(lol())中第一次被调用时会终止? –

+0

它会打印两次,尝试'print_twice('foo')',你只需要确保它的参数是一个字符串,在这种情况下你可以改变'lol',这样它就会返回一些东西。 'def lol:return'foo'' then'print_twice(lol())'会打印'foo'两次。 –

0

如何预期您可能会遇到:

def lol(): 
    print "lol" 

def run_twice(func): 
    func() 
    func() 

run_twice(lol)