Python参数和函数

Cap*_*uzz 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())    
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我的输出是:

-1.0
I hope this works
None
None
Run Code Online (Sandbox Code Playgroud)

怎么不打印函数lol()两次?

Joh*_*die 7

你的代码print_twice(lol())说要执行lol()并将其返回值传递给print_twice().由于您没有为其指定返回值lol(),因此返回None.因此,lol()在执行时打印一次,并且print中的两个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)
Run Code Online (Sandbox Code Playgroud)

取而代之的传递返回值lol(),我们现在传递的功能 lol,这是我们在随后两次执行print_twice().