为什么这个def函数在Python中没有被执行?
当我在输入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 个回答
1
把最后几行的缩进去掉。因为它们现在有缩进,所以被认为是print_none()
这个函数的一部分,而不是在全局范围内执行。把它们放回全局范围后,你就能看到它们正常运行了。
2
def 是用来定义一个函数的。函数就像是一组步骤,准备好随时可以执行。要在 Python 中执行一个函数,首先必须定义它,然后再调用它。
# this one takes no argument
def print_none() :
print "I got nothin'."
#brings up prompt..then execute it
print_none()
4
最后四行的缩进是错误的。因为它们有缩进,Python解释器认为它们是print_none()
这个函数的一部分。把它们的缩进去掉,解释器就会按预期调用它们。应该是这样的:
>>> print_two("Zed","Shaw")
[... etc ...]