2011-03-23 126 views
0

Python是简单地造就另一个提示,当我从Zed的肖锻炼18为什么这个def函数没有在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() 
+1

对不起,*其中*一段代码?你在Python REPL中输入了所有的东西吗? – 2011-03-23 03:12:30

+0

哪段代码? – 2011-03-23 03:12:55

+0

@senderle对此表示歉意!感谢您的支持! – 2011-04-13 03:00:13

回答

4

最后四行的缩进是错误输入下面的一段代码。由于它们缩进,python解释器认为它们是print_none()的一部分。取消他们的意图,口译员会按照预期给他们打电话。它应该看起来像这样:

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

是的我只是想通了,我是一个涂料。非常感谢。 – 2011-03-23 03:17:03

1

def定义了一个函数。函数是潜在的......他们有一系列等待执行的步骤。 要在python中执行一个函数,它必须被定义,并且被称为

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

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

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

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() 
相关问题