为什么这个def函数没有在Python中执行?

时间:2011-03-23 03:10:39

标签: python function

当我从Zed Shaw练习18输入以下代码时,Python只是提示另一个提示。

# this one is like our scripts with argv
def print_two(*args):
    arg1, arg2 = args
    print "arg1: %r, arg2: %r" % (arg1, arg2)

# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2) :
    print "arg1: %r, arg2: %r" % (arg1, arg2)

# this just takes one argument
def print_one(arg1) :
    print "arg1: %r" % arg1

# this one takes no argument
def print_none() :
    print "I got nothin'."


    print_two("Zed","Shaw")
    print_two_again("Zed","Shaw")
    print_one("First!")
    print_none()

4 个答案:

答案 0 :(得分:4)

最后四行的缩进是错误的。因为它们是缩进的,所以python解释器认为它们是print_none()的一部分。取消他们,翻译将按预期称呼他们。它应该是这样的:

>>> print_two("Zed","Shaw")
[... etc ...]

答案 1 :(得分:1)

def定义一个函数。功能是潜在的......它们是一组等待执行的步骤。 要在python中执行函数,必须定义它并调用

# this one takes no argument
def print_none() :
    print "I got nothin'."

#brings up prompt..then execute it
print_none()

答案 2 :(得分:1)

删除最后一行的缩进。因为它们是缩进的,所以它们是print_none()的一部分,而不是在全局范围内执行。一旦他们回到全球范围,您应该看到它们正在运行。

答案 3 :(得分:1)

您需要保持代码一致。您调用上述方法被视为函数print_none()的一部分。

试试这个:

    # this one is like our scripts with argv
def print_two(*args):
    arg1, arg2 = args
    print "arg1: %r, arg2: %r" % (arg1, arg2)

# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2) :
    print "arg1: %r, arg2: %r" % (arg1, arg2)

# this just takes one argument
def print_one(arg1) :
    print "arg1: %r" % arg1

# this one takes no argument
def print_none() :
    print "I got nothin'."


print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()